Click here for the blog article: Summary of string format methods in python3
I couldn't remember it easily and it was hard so I decided to write it down and put it together. I pray that the retention in my memory will be even a little decent. ..
'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
Attach the format method after the string. The place to insert is basically specified by ** {} **.
'This is our string {}'.format('in Python')
'{} {} {}'.format('a','b','c')
# 'a b c'
'{2} {1} {0}'.format('a','b','c')
#c b a
#You can specify like an index
'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
I use the format method, but it seems that I can do more than I expected.
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
#Prepare 50 indexes and enter characters left-justified
'{:a<50}.format('aligned left ')
#'aligned left aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
#The top is hard to see, so I filled it with 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'
#It seems that the result of division can also be displayed
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%'
Magnificent note-taking. For the time being, I want to be able to put it in my head and use it.
Recommended Posts