Python中字符串格式化的方法有哪些

小億
85
2024-03-06 12:35:01

在Python中,字符串格式化的方法有以下幾種:

  1. 使用%操作符進(jìn)行格式化,例如:
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old" % (name, age)
print(formatted_string)
  1. 使用str.format()方法進(jìn)行格式化,例如:
name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old".format(name, age)
print(formatted_string)
  1. 使用f-strings進(jìn)行格式化,例如:
name = "Charlie"
age = 20
formatted_string = f"My name is {name} and I am {age} years old"
print(formatted_string)
  1. 使用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)
  1. 使用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)

0