# 示例代码:使用 format 方法进行字符串格式化
# 基本用法:位置参数
name = "Alice"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string) # 输出: My name is Alice and I am 30 years old.
# 使用索引参数
formatted_string = "My name is {0} and I am {1} years old. Hello, {0}!".format(name, age)
print(formatted_string) # 输出: My name is Alice and I am 30 years old. Hello, Alice!
# 使用关键字参数
formatted_string = "My name is {name} and I am {age} years old.".format(name="Bob", age=25)
print(formatted_string) # 输出: My name is Bob and I am 25 years old.
# 格式化数字
pi = 3.141592653589793
formatted_string = "The value of pi is approximately {:.2f}".format(pi)
print(formatted_string) # 输出: The value of pi is approximately 3.14
format
是 Python 中用于字符串格式化的方法。{}
占位符将变量插入到字符串中。下一篇:python列表遍历
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站