当进行字符串格式化时,可以使用多种方式。以下是一些常见的Python字符串格式化示例:
使用百分号(%)格式化:
name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age))
输出:My name is Alice and I'm 25 years old.
使用f-string格式化(Python 3.6+):
name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old.")
输出:My name is Alice and I'm 25 years old.
使用format()
方法格式化:
name = "Alice"
age = 25
print("My name is {} and I'm {} years old.".format(name, age))
输出:My name is Alice and I'm 25 years old.
指定格式选项:
number = 3.14159
print("The value of pi is approximately {:.2f}".format(number))
输出:The value of pi is approximately 3.14
这些示例涵盖了常见的字符串格式化方法。根据你的具体需求,选择适合的方法进行字符串格式化。
当然!以下是更多的 Python 字符串格式化示例:
对齐文本:
name = "Alice"
print("Hello, {:^10}!".format(name)) # 居中对齐
print("Hello, {:>10}!".format(nam)) # 右对齐
print("Hello, {:<10}!".format(name)) # 左对齐
输出:
Hello, Alice !
Hello, Alice!
Hello, Alice !
使用千位分隔符:
number = 1000000
print("The population is {:,}".format(number))
输出:The population is 1,000,000
使用进制格式:
number = 42
print("The answer is {:b}".format(number)) # 二进制
print("The answer is {:o}".format(number)) # 八进制
print("The answer is {:x}".format(number)) # 十六进制
输出:
The answer is 101010
The answer is 52
The answer is 2a
使用变量属性:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 25)
print("My name is {person.name} and I'm {person.age} years old.")
输出:My name is Alice and I'm 25 years old.
这些示例展示了更多的字符串格式化选项,例如对齐文本、使用千位分隔符、进制格式等。根据你的具体需求,你可以选择适当的选项进行字符串格式化。希望这可以帮助到你!
原文链接:codingdict.net