Python3.6新特性,字符串f前缀

f前缀用来格式化字符串,例如

>>> name = 'Fred'
>>> age = 42
>>> f'He said his name is {name} and he is {age} years old.'
He said his name is Fred and he is 42 years old.

可以看出f前缀可以简单有效的格式化字符串,比起format()方法具备更好的可读性

>>> name = 'Fred'
>>> age = 42
>>> 'He said his name is {} and he is {} years old.'.format(name, age)
'He said his name is Fred and he is 42 years old.'

而且加上f前缀后,支持在大括号内,运行Python表达式

>>> name = 'Fred'
>>> seven = 7
>>> f'''He said his name is {name.upper()}
...    and he is {6 * seven} years old.'''
'He said his name is FRED\n    and he is 42 years old.'

你还可以用fr前缀来表示来表示原生字符串


参考(The new f-strings in Python 3.6)[https://cito.github.io/blog/f-strings/]

你可能感兴趣的:(Python3.6新特性,字符串f前缀)