In [1]:
a = 123
In [2]:
b = 'abc'
In [3]:
print('{} and {}'.format(a, b))
In [4]:
print('{first} and {second}'.format(first=a, second=b))
In [5]:
print(f'{a} and {b}')
In [6]:
print(F'{a} and {b}')
In [7]:
print(f"{a} and {b}")
In [8]:
print(f'''{a} and {b}''')
In [9]:
print(f"""{a} and {b}""")
In [10]:
s = 'abc'
In [11]:
print(f'right : {s:_>8}')
print(f'center: {s:_^8}')
print(f'left : {s:_<8}')
In [12]:
i = 1234
In [13]:
print(f'zero padding: {i:08}')
In [14]:
print(f'comma: {i:,}')
In [15]:
print(f'bin: {i:b}')
print(f'oct: {i:o}')
print(f'hex: {i:x}')
In [16]:
print(f'bin: {i:#b}')
print(f'oct: {i:#o}')
print(f'hex: {i:#x}')
In [17]:
f = 12.3456
In [18]:
print(f'digit(decimal): {f:.3f}')
print(f'digit(all) : {f:.3g}')
In [19]:
print(f'exponen: {f:.3e}')
In [20]:
f = 0.123
print(f'percent: {f:.2%}')
In [21]:
n = 123
In [22]:
print(f'{{}}-{n}-{{{n}}}')
In [23]:
n = 123
i = 8
In [24]:
print('{n:0{i}}'.format(n=n, i=i))
In [25]:
print(f'{n:0{i}}')
In [26]:
f = 1.2345
for i in range(5):
print(f'{f:.{i}f}')
In [27]:
print('x\ty')
In [28]:
print(r'x\ty')
In [29]:
x = 'XXX'
y = 'YYY'
In [30]:
print(f'{x}\t{y}')
In [31]:
print(rf'{x}\t{y}')
In [32]:
print(fr'{x}\t{y}')
In [33]:
a = 3
b = 4
In [34]:
# print('{a} + {b} = {a + b}'.format(a=a, b=b))
# KeyError: 'a + b'
In [35]:
print(f'{a} + {b} = {a + b}')
In [36]:
print(f'{a} * {b} = {a * b}')
In [37]:
print(f'{a} / {b} = {a / b:.2e}')
In [38]:
d = {'key1': 3, 'key2': 4}
In [39]:
print('{0[key1]}, {0[key2]}'.format(d))
In [40]:
# print('{0["key1"]}, {0["key2"]}'.format(d))
# KeyError: '"key1"'
In [41]:
print(f'{d["key1"]}, {d["key2"]}')
In [42]:
# print(f'{d[key1]}, {d[key2]}')
# NameError: name 'key1' is not defined
In [43]:
# print(f'{d['key1']}, {d['key2']}')
# SyntaxError: invalid syntax
In [44]:
print(f"{d['key1']}, {d['key2']}")
In [45]:
# print(f'{d[\'key1\']}, {d[\'key2\']}')
# SyntaxError: f-string expression part cannot include a backslash