码迷,mamicode.com
首页 > 编程语言 > 详细

python3.6使用f-string来格式化字符串

时间:2019-03-14 09:16:31      阅读:335      评论:0      收藏:0      [点我收藏+]

标签:import   官方文档   支持   表达式   result   int   format   syntax   print   

这里的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来格式化字符串

标签:import   官方文档   支持   表达式   result   int   format   syntax   print   

原文地址:https://www.cnblogs.com/linyihai/p/10527721.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!