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'

猜你喜欢

转载自www.cnblogs.com/linyihai/p/10527721.html
今日推荐