Python 3.6中的格式化字符串文字是什么?

Gün*_*ena 17 python python-3.6 f-string

Python 3.6的一个功能是格式化字符串.

这个SO问题(python-3.6中带有'f'前缀的字符串)询问格式化字符串文字的内部,但我不理解格式化字符串文字的确切用例.我应该在哪些情况下使用此功能?不明确比隐含更好吗?

xmc*_*mcp 28

简单比复杂更好.

所以这里我们有格式化字符串.它为字符串格式提供了简单性,同时保持代码显式(与其他字符串格式化机制的硬件).

title = 'Mr.'
name = 'Tom'
count = 3

# This is explicit but complex
print('Hello {title} {name}! You have {count} messages.'.format(title=title, name=name, count=count))

# This is simple but implicit
print('Hello %s %s! You have %d messages.' % (title, name, count))

# This is both explicit and simple. PERFECT!
print(f'Hello {title} {name}! You have {count} messages.')
Run Code Online (Sandbox Code Playgroud)

它旨在取代str.format简单的字符串格式.

  • 好吧,当你在字符串中有十几个`{}`时,它是非常"隐含的" (3认同)