python

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

小亿
85
2024-03-06 12:35:01
栏目: 编程语言

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

  1. 使用%操作符进行格式化,例如:
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old" % (name, age)
print(formatted_string)
  1. 使用str.format()方法进行格式化,例如:
name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old".format(name, age)
print(formatted_string)
  1. 使用f-strings进行格式化,例如:
name = "Charlie"
age = 20
formatted_string = f"My name is {name} and I am {age} years old"
print(formatted_string)
  1. 使用format()方法和位置参数进行格式化,例如:
name = "David"
age = 35
formatted_string = "My name is {0} and I am {1} years old".format(name, age)
print(formatted_string)
  1. 使用format()方法和关键字参数进行格式化,例如:
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
看了该问题的人还看了