f-string ,Python3.6中新增的比%和format方式更好的格式化输出方式

详细内容参阅手册.

https://docs.python.org/3/reference/lexical_analysis.html#f-strings

手册中的一些例子

>>> 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'
>>> f"{today=:%B %d, %Y}" # using date format specifier and debugging
'today=January 27, 2017'
>>> number = 1024
>>> f"{number:#0x}"  # using integer format specifier
'0x400'
>>> foo = "bar"
>>> f"{ foo = }" # preserves whitespace
" foo = 'bar'"
>>> line = "The mill's closed"
>>> f"{line = }"
'line = "The mill\'s closed"'
>>> f"{line = :20}"
"line = The mill's closed   "
>>> f"{line = !r:20}"
'line = "The mill\'s closed" '

  比较易读的,点击这个https://realpython.com/python-f-strings/#arbitrary-expressions

 

posted @ 2021-03-09 11:17  歪理斜说  阅读(93)  评论(0编辑  收藏  举报