美文网首页
Python3.6新特性,字符串f前缀

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

作者: xiaoyaook | 来源:发表于2017-10-25 20:31 被阅读0次

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前缀

      本文链接:https://www.haomeiwen.com/subject/hpdcpxtx.html