阅读量:0
在Python中,字符串格式化的方法有以下几种:
- 使用
%
操作符进行格式化,例如:
name = "Alice" age = 30 formatted_string = "My name is %s and I am %d years old" % (name, age) print(formatted_string)
- 使用
str.format()
方法进行格式化,例如:
name = "Bob" age = 25 formatted_string = "My name is {} and I am {} years old".format(name, age) print(formatted_string)
- 使用f-strings进行格式化,例如:
name = "Charlie" age = 20 formatted_string = f"My name is {name} and I am {age} years old" print(formatted_string)
- 使用
format()
方法和位置参数进行格式化,例如:
name = "David" age = 35 formatted_string = "My name is {0} and I am {1} years old".format(name, age) print(formatted_string)
- 使用
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)