在Python中,字符串格式化可以通过多种方法实现,以下是几种常见的方法:
name = "Alice"
age = 30
formatted_str = "My name is %s and I am %d years old." % (name, age)
print(formatted_str) 输出:My name is Alice and I am 30 years old.
2. 使用`str.format()`方法格式化:
name = "Alice"
age = 30
formatted_str = "My name is {} and I am {} years old.".format(name, age)
print(formatted_str) 输出:My name is Alice and I am 30 years old.
3. 使用f-字符串格式化(Python 3.6+):
name = "Alice"
age = 30
formatted_str = f"My name is {name} and I am {age} years old."
print(formatted_str) 输出:My name is Alice and I am 30 years old.
4. 使用`center()`、`ljust()`和`rjust()`方法进行字符串对齐:
text = "Python"
print(text.center(20)) 输出:Python
print(text.ljust(20)) 输出:Python
print(text.rjust(20)) 输出:Python
5. 使用`zfill()`方法对数字字符串左补0:
number = 123
print(str(number).zfill(5)) 输出:00123
以上方法都可以用来格式化输出字符串。选择哪种方法取决于你的具体需求和个人偏好