ゆーかん

徒然日記

python3での文字列フォーマットの方法まとめ

昔ながらのやり方(まだ使われてるけど)

'This is our %s' % 'string'
  # This is our string

print('we are learning %s %s' % ('Python', '3'))
  # we are learning Python 3

print('we are learning %(lang)s %(ver)s' % {'lang': 'Python', 'ver': '3'})
  #we are learning Python 3

新型 (推奨されてるやり方)

文字列の後ろに formatメソッドをくっつける。 挿入する場所は基本的に { }にて指定する。

'This is our string {}'.format('in Python')

'{} {} {}'.format('a','b','c') 
  # 'a b c'

'{2} {1} {0}'.format('a','b','c') 
  #c b a
  #インデックスみたいな指定ができる

'we are learning {lang} {ver}'.format(lang = 'Python', version = '3') 
  #we are learning Python 3

language = ('Python', '3')
'we are learning {0[0]} {0[1]}'.format(language)
  #we are learning Python 3

上級編

formatメソッドを使うんだけど、思ったよりたくさんのことができるらしい。

  • 数字をバイナリーに変換
  • 左寄せ・右寄せ・中央寄せとかで文字列作成
animal = ('Dog', 'Cat')
name = ('Maggie', 'Missy')

'I have a {0[0]} named {1[0]}'.format(animal,name)
    #I have a dog named Maggie

'I have a {0[1]} named {1[1]}'.format(animal,name)
    #I have a cat named Missy

'{:<50}'.format('aligned left')
  #'aligned left          
  #50インデックス用意して左詰めで文字入力
                            '{:a<50}.format('aligned left ')
  #'aligned left aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
  #上のが見づらいのでaで埋めてみた

'{:>50}'.format('aligned right')

'{:^50}'.format('aligned center')

'{:$^50}'.format('More Money')
  #'$$$$$$$$$$$$$$$$$$$$More Money$$$$$$$$$$$$$$$$$$$$'

'Binary: {0:b}'.format(324)
    #Binary: 101000100

'{:,}'.format(123456787654321)
    #'123,456,787,654,321'

  #割り算した結果も表示できるらしい
correct = 78
total = 84
'Your score is: {:.1%}'.format(correct/total)
    #'Your score is: 92.9%'
'Your score is: {:.3%}'.format(correct/total)
    #'Your score is 92.857%'

Qiitaの記事はこちらPython3での文字列フォーマットまとめ 旧型で生きるか、新型で生きるか