f-string is a string literal added from python3.6. The feature is to add f or F at the beginning outside the character string.
>>> name = 'GAO'
>>> age = 24
>>> f'Hello{name}is,{age}I'm talented.'
'Hello GAO, is 24 years old.'
>>> years_later = 10
>>> f'{years_later}Years later{age + years_later}I'm talented.'
'Ten years later, I will be 34 years old.'
>>> def one_year_later(current_age):
... return current_age + 1
...
>>> f'next year{one_year_later(age)}I'm talented.'
'I will be 25 next year.'
>>> f'{name}To lowercase{name.lower()}is.'
'Lowercase GAO is gao.'
>>> jikoshoukai = f'Hello{name}is,{age}I'm talented.' \
... f'{years_later}Years later{age + years_later}I'm talented.' \
... f'next year{one_year_later(age)}I'm talented.' \
... f'{name}To lowercase{name.lower()}is.'
>>> jikoshoukai
'Hello GAO, is 24 years old. Ten years later, I will be 34 years old. I will be 25 next year. Lowercase GAO is gao.'
>>> a = 123
>>> f'8 digits padded with zeros: {a:08}'
'Zero padding: 00000123'
>>> for i in range(4,8):
... f'Zero padding{i}digit: {a:0{i}}'
...
'4 digits padded with zeros: 0123'
'Zero padded 5 digits: 00123'
'6 digits padded with zeros: 000123'
'7 digits padded with zeros: 0000123'
>>> a = 123.456789
>>> f'4 digits after the decimal point: {a:.4f}'
'Decimal places: 123.4568'
>>> f'4 effective digits: {a:.4g}'
'Effective digit: 123.5'
Recommended Posts