在Python中,字符串格式化的方法有以下幾種:
%
操作符進(jìn)行格式化,例如:name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old" % (name, age)
print(formatted_string)
str.format()
方法進(jìn)行格式化,例如:name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old".format(name, age)
print(formatted_string)
name = "Charlie"
age = 20
formatted_string = f"My name is {name} and I am {age} years old"
print(formatted_string)
format()
方法和位置參數(shù)進(jìn)行格式化,例如:name = "David"
age = 35
formatted_string = "My name is {0} and I am {1} years old".format(name, age)
print(formatted_string)
format()
方法和關(guān)鍵字參數(shù)進(jìn)行格式化,例如:name = "Eve"
age = 40
formatted_string = "My name is {name} and I am {age} years old".format(name=name, age=age)
print(formatted_string)