是的,Python的print方法可以使用字符串格式化來輸出。
常用的字符串格式化方法有:
%格式化:使用%運(yùn)算符將變量插入到字符串中。例如:
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
輸出結(jié)果為:My name is Alice and I am 25 years old.
str.format()方法:使用str.format()方法將變量插入到字符串中。例如:
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
輸出結(jié)果為:My name is Alice and I am 25 years old.
f-string(Python 3.6+):使用f-string將變量嵌入到字符串字面值中。例如:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
輸出結(jié)果為:My name is Alice and I am 25 years old.