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

标签 python python-3.6 f-string

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/

相关文章:

python - 将 NumPy 数组的指定元素转换为新值

visual-studio-2015 - 如何将 Python 语言版本添加到环境中?

python - 使用函数 multiprocessing.Pool 在 python 中出现奇怪的结果?

Python3 pip3 安装在 Ubuntu 上损坏

python - 如何在matplotlib中显示LaTeX f字符串

Python:如何按数字顺序对 .txt 文件的内容进行排序?

python - 我可以使用 Hendrix 运行 Falcon 应用程序吗?

python - Seaborn:在直方图上叠加箱线图或均值误差条

python - 为什么在内部打印时\n 只在 f 字符串中工作?

python - 在 f 字符串中转义单括号