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来格式化字符串的主要内容,如果未能解决你的问题,请参考以下文章

Python3.6新特性:f-strings格式化输出

Python格式化字符串f-string常用用法

Python3 字符串三种格式化技巧

在 Python 格式(f-string)字符串中,!r 是啥意思? [复制]

f-strings格式化输出

这些 f-string 的用法,90% 的 Pythoner 不知道!