python3.6使用f-string来格式化字符串
Posted lyh225
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3.6使用f-string来格式化字符串相关的知识,希望对你有一定的参考价值。
这里的f-string指的是以f或F修饰的字符串,在字符串中使用{}来替换变量,表达式和支持各种格式的输出。详细的格式化定义可以看官方文档
>>> a, b = 30, 20
>>> print(f"the result of 30 - 20 is {a - b}")
the result of 30 - 20 is 10
>>> import datetime
>>> print(f"now is {datetime.datetime.today()}")
now is 2019-03-14 00:49:44.853937
>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is 'Fred'."
>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
"He said his name is 'Fred'."
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
'result: 12.35'
>>> today = datetime(year=2017, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
'January 27, 2017'
>>> number = 1024
>>> f"{number:#0x}" # using integer format specifier
'0x400'
以上是关于python3.6使用f-string来格式化字符串的主要内容,如果未能解决你的问题,请参考以下文章