阅读量:0
Python的format函数可以用来格式化字符串。以下是使用format函数的示例:
- 使用位置参数:
name = "Alice" age = 30 message = "My name is {} and I am {} years old.".format(name, age) print(message)
输出结果为:My name is Alice and I am 30 years old.
- 使用关键字参数:
name = "Bob" age = 25 message = "My name is {name} and I am {age} years old.".format(name=name, age=age) print(message)
输出结果为:My name is Bob and I am 25 years old.
- 使用索引:
name = "Charlie" age = 20 message = "My name is {0} and I am {1} years old.".format(name, age) print(message)
输出结果为:My name is Charlie and I am 20 years old.
- 格式化数字:
pi = 3.14159 formatted_pi = "Pi is approximately {:.2f}".format(pi) print(formatted_pi)
输出结果为:Pi is approximately 3.14
以上是使用format函数的一些常见示例,你可以根据自己的需求来选择合适的方式来格式化字符串。