%。
格式化(旧格式化)name。 ="Alice"age。 =30。formatted_string。 ="Name: %s, Age: %d"%。(。name。,age。)。print。(。formatted_string。)。# 输出: Name: Alice, Age: 30。
pi。 =3.141592653589793。formatted_string。 ="Pi: %f"%。pi。print。(。formatted_string。)。# 输出: Pi: 3.141593。formatted_string。 ="Pi: %.2f"%。pi。print。(。formatted_string。)。# 输出: Pi: 3.14。
%f。
表示浮点数默认情况下显示六位小数。%.2f.
保留两位小数。formatted_string。 ="|s|"%。"test"# 右对齐,宽度为 10。print。(。formatted_string。)。# 输出: | test|。formatted_string。 ="|%-10s|#344;%。"test"# 左对齐,宽度为 10。print。(。formatted_string。)。# 输出: |test |。
s。
表示字段宽度为 10,右对齐。%-10s。
表示字段宽度为 10,左对齐。str.format()。
方法(更新格式化)name。 ="Bob"age。 =25。formatted_string。 ="Name: { }, Age: { }".。format。(。name。,age。)。print。(。formatted_string。)。# 输出: Name: Bob, Age: 25。
formatted_string。 ="Name: { 0}, Age: { 1}".。format。(。name。,age。)。print。(。formatted_string。)。# 输出: Name: Bob, Age: 25。formatted_string。 ="Name: { name}, Age: { age}".。format。(。name。="Carol",age。=28。)。print。(。formatted_string。)。# 输出: Name: Carol, Age: 28。
{ 0}。
和。 { 1}。
索引指定位置参数。{ name}。
和。 { age}。
使用关键字参数。pi。 =3.141592653589793。formatted_string。 ="Pi: { :.2f}".。format。(。pi。)。print。(。formatted_string。)。# 输出: Pi: 3.14。
formatted_string。 ="|{ :10}|".。format。(。"test")。# 右对齐,宽度为 10。print。(。formatted_string。)。# 输出: | test|。formatted_string。 ="|{ :<10}|".。format。(。"test")。# 左对齐,宽度为 10。print。(。formatted_string。)。# 输出: |test |。
{ :10}。
表示字段宽度为 10,右对齐。{ :10}。
默认右对齐{ :<10}。
左对齐。text。 ="Hello"formatted_string。 ="{ :.3}".。format。(。text。)。# 截取前三个字符。print。(。formatted_string。)。# 输出: Hel。
{ :.3}。
表示截取前三个字符。name。 ="Dave"age。 =40。formatted_string。 =f"Name:。 { 。10。}。}。"print。(。formatted_string。)。# 输出: Value is 123。
value:{ 10}。
表示字段宽度为 10。string.Template。
类)from。string。 import。Templatetemplate。 =Template。(。"Name: $name, Age: $age")。formatted_string。 =template。.。substitute。(。name。="Eva",age。=22。)。print。(。formatted_string。)。# 输出: Name: Eva, Age: 22。
template。 =Template。(。"Hello, $name! Welcome to $place.")。formatted_string。 =template。.。substitute。(。name。="John",place。="Python Land")。print。(。formatted_string。)。# 输出: Hello, John! Welcome to Python Land.。
$。
符号。template。 =Template。(。"The price is $$100")。formatted_string。 =template。.。substitute。(。)。print。(。formatted_string。)。# 输出: The price is $100。
$$。
用于插入实际。 $。
符号。template。 =Template。(。"Name: $name, Age: ${ age}")。formatted_string。 =template。.。safe_substitute。(。name。="Julia")。print。(。formatted_string。)。# 输出: Name: Julia, Age: ${ age}。
safe_substitute。
用于在缺失值时不抛出异常,用原始占位符代替。%。
格式化。str.format()。
string.Template。
在 Python 中,可根据具体需要选择不同的格式化方法。%。
格式化适用于简单场景,str.format()。
它提供了更多的灵活性和功能,而 f-strings 是现代 Python 推荐的格式化方式,由于其简洁,性能优越。string.Template。
适用于需要处理用户输入的情况。