文章摘要
本文介绍了Python中f-string的格式化用法,重点展示了如何对数字进行格式化。通过示例表格,详细说明了不同格式化选项(如填充、宽度、分组、精度和类型)对输出结果的影响,适用于整数和浮点数。例如,使用.2f可以保留两位小数,而.2g则用于科学计数法显示。
文章总结
Python f-string 速查表
本文提供了Python中f-string的格式化用法示例,涵盖了数字、整数、字符串以及所有对象类型的格式化操作。以下为主要内容:
数字格式化
假设有以下变量:
python
number = 4125.6
percent = 0.3738
示例包括:
- {number:.2f} 输出 '4125.60',保留两位小数。
- {number:,.2f} 输出 '4,125.60',使用千位分隔符并保留两位小数。
- {number:08.2f} 输出 '04125.60',用0填充至8位并保留两位小数。
- {percent:.0%} 输出 '37%',将小数转换为百分比并保留整数部分。
整数格式化
假设有以下变量:
python
number = 10
示例包括:
- {number:04d} 输出 '0010',用0填充至4位。
- {number:b} 输出 '1010',将整数转换为二进制。
- {number:x} 输出 'a',将整数转换为小写十六进制。
- {number:#x} 输出 '0xa',显示十六进制前缀。
字符串格式化
假设有以下变量:
python
string = "Python"
示例包括:
- {string:>20} 输出 ' Python',右对齐并填充至20位。
- {string:<20} 输出 'Python ',左对齐并填充至20位。
- {string:0>10} 输出 '0000Python',用0填充至10位并右对齐。
所有对象格式化
示例包括:
- {expression!s} 输出 'Hi! ✨',使用str()转换。
- {expression!r} 输出 "'Hi! ✨'",使用repr()转换。
- {expression=} 输出 "name='Trey'",自文档化表达式。
更多详细示例和讨论可参考fstring.help和字符串格式化文章。
评论总结
评论主要围绕Python的f-strings展开,观点分为支持和批评两派。
支持观点: 1. f-strings的强大与便利:多位评论者认为f-strings非常强大且易于使用,尤其是在字符串格式化时提供了上下文感知的优势。 - "f-strings put the value in the output string exactly where the value should be. Massive win for contextual awareness." (jonathaneunice) - "I love python f-strings. I dont use the format specifiers that this article points out." (ilovetux)
- f-strings的灵活性:一些评论者提到f-strings的灵活性,尤其是在调试和测试中的应用。
- "It will let me know if there is some code path where the proper variable is never set." (ilovetux)
批评观点: 1. f-strings的复杂性:部分评论者认为f-strings的语法过于复杂,甚至比旧的字符串格式化方法更难理解。 - "I think f-strings have become the thing they were trying to replace and they are now more complicated than the old % interpolation." (nickcw) - "This looks like a cheatsheet for writing a hard-to-read Python script." (roenxi)
- f-strings的适用性:有评论者质疑f-strings的适用性,认为在某些情况下使用其他方法(如
rjust()或printf)更为合适。- "I fail to see the purpose of f-strings if they end up as complex as printf formatting. Maybe use printf at this point?" (blueflow)
中立观点: 1. f-strings的学习曲线:一些评论者提到f-strings的学习曲线,认为虽然功能强大,但需要一定的学习和记忆。 - "Ah, these are great! f-strings are so powerful, but I can never remember the arcane little syntax." (xavdid) - "I use them and I discovered a few that I did not know." (jokoon)
总结来看,f-strings在Python社区中既有支持者也有批评者,支持者认为其强大且灵活,而批评者则认为其复杂且不易读。