** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
{}
and .format ()
>>> 'A is {}.' .format('a')
'A is a.'
>>> 'A is {}.' .format('test')
'A is test.'
The character string specified by .format ()
is assigned to the part of {}
.
>>> 'My name is {} {}.' .format('Tony', 'Stark')
'My name is Tony Stark.'
>>> 'My name is {0} {1}.' .format('Tony', 'Stark')
'My name is Tony Stark.'
>>> 'My name is {0} {1}. Watashi ha {1} {0} desu.' .format('Tony', 'Stark')
'My name is Tony Stark. Watashi ha Stark Tony desu.'
If there are multiple {}
, they are assigned in order from the front.
If you specify an index, the character string corresponding to that index will be assigned.
>>>Watashi ha {family} {name} desu.' .format(name = 'Tony', family = 'Stark')
Watashi ha Stark Tony desu.'
>>> type('1')
<class 'str'>
>>> type(1)
<class 'int'>
>>> '{}, {}, {}, Go!' .format('1', '2', '3')
'1, 2, 3, Go!'
>>> '{}, {}, {}, Go!' .format(1, 2, 3)
'1, 2, 3, Go!'
1
is an int type, but it is converted to a str type and assigned.
■f-strings Starting with Python 3.6, f-strings can be used as follows.
f-strings
a = 'a'
print(f'a is {a}')
x, y, z = 1, 2, 3
print(f'a is {x}, {y}, {z}')
print(f'a is {z}, {y}, {x}')
name = 'Tony'
family = 'Stark'
print(f'My name is {name} {family}. Watashi ha {family} {name} desu.')
result
a is a
a is 1, 2, 3
a is 3, 2, 1
My name is Tony Stark. Watashi ha Stark Tony desu.
Recommended Posts