Python 3.6 的一个特性是格式化字符串。
This SO question (python-3.6 中带有 'f' 前缀的字符串)正在询问格式化字符串文字的内部结构,但我不了解格式化字符串文字的确切用例。我应该在哪些情况下使用此功能?显式不是比隐式更好吗?
最佳答案
Simple is better than complex.
所以这里我们已经格式化了字符串。它使字符串格式化变得简单,同时保持代码明确(与其他字符串格式化机制相比)。
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.')
它旨在替换 str.format
进行简单的字符串格式化。
关于python - Python 3.6 中的格式化字符串文字是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39081766/