Python の format関数で置換後の幅を指定する方法は、
{:n}
と、: の後に幅 n を指定する。
print('1234567890') print('{:5}'.format('A')+"-") # 1234567890 # A -
となる。
数値を千の単位で、カンマを差し込む時は、
{:,}
print('{:,}'.format(123456)) # 123,456
実践を考えて、数字の後に'円'が付くものだけを対象にする場合で
さらに表示幅を大きくして揃えたい。
編集前のテキスト、、
txt = 'id=1023 price:1000円\n' \ 'id=1024 price:300円\n' \ 'id=1025 price:210500円\n' \ 'id=1026 price:1500000円\n'
関数を定義して
def priceRepl(m): return '{:11,}'.format(int(m.group().replace('円', ''))) + ' 円' result = re.sub(r'[0-9]+円', priceRepl, txt) print(result) # id=1023 price: 1,000 円 # id=1024 price: 300 円 # id=1025 price: 210,500 円 # id=1026 price: 1,500,000 円
関数なんか定義せずにラムダで、、
result = re.sub(r'[0-9]+円', lambda m:'{:11,}'.format(int(m.group().replace('円', '')))+' 円', txt) print(result) # id=1023 price: 1,000 円 # id=1024 price: 300 円 # id=1025 price: 210,500 円 # id=1026 price: 1,500,000 円