字符串格式化在Python中用于美化输出,f-strings(推荐)、.format()和%运算符可插入变量并控制显示格式,包括精度、对齐及日期时间格式化。

字符串格式化在Python中,说白了,就是让你的输出更漂亮、更易读。它允许你将变量的值插入到字符串中,并控制它们的显示方式,比如精度、对齐方式等等。
字符串格式化技巧
f-strings 是 Python 3.6 引入的一种简洁高效的字符串格式化方式。它通过在字符串前加上
f
f
{}name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")f-strings 的优势在于其可读性和简洁性。你可以在花括号内直接进行运算或调用函数:
立即学习“Python免费学习笔记(深入)”;
x = 10
y = 5
print(f"The sum of {x} and {y} is {x + y}.").format()
.format()
{}.format()
name = "Bob"
age = 25
print("My name is {} and I am {} years old.".format(name, age))你可以使用索引来指定插入值的顺序:
print("My name is {1} and I am {0} years old.".format(age, name))或者使用关键字参数:
print("My name is {name} and I am {age} years old.".format(name="Charlie", age=40)).format()
%
%
printf
.format()
name = "David"
age = 35
print("My name is %s and I am %d years old." % (name, age))其中,
%s
%d
在格式化浮点数时,你可能需要控制其精度。可以使用 f-strings 或
.format()
使用 f-strings:
pi = 3.1415926535
print(f"The value of pi is approximately {pi:.2f}.") # 输出 3.14使用
.format()
pi = 3.1415926535
print("The value of pi is approximately {:.2f}.".format(pi)) # 输出 3.14:.2f
字符串格式化还允许你控制字符串的对齐方式和填充字符。
使用 f-strings:
num = 42
print(f"{num: >4}") # 右对齐,总宽度为4,用空格填充
print(f"{num:0>4}") # 右对齐,总宽度为4,用0填充
print(f"{num: <4}") # 左对齐,总宽度为4,用空格填充
print(f"{num:^4}") # 居中对齐,总宽度为4,用空格填充使用
.format()
num = 42
print("{: >4}".format(num)) # 右对齐,总宽度为4,用空格填充
print("{:0>4}".format(num)) # 右对齐,总宽度为4,用0填充
print("{: <4}".format(num)) # 左对齐,总宽度为4,用空格填充
print("{:^4}".format(num)) # 居中对齐,总宽度为4,用空格填充>
<
^
Python 的
datetime
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 输出 2023-10-27 10:30:00 (示例)strftime()
%Y
%m
%d
%H
%m
%s
总而言之,选择哪种方法取决于你的具体需求和 Python 版本。但是,掌握 f-strings 和
.format()
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号