# 示例代码:使用 str.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_with_index = "My name is {0} and I am {1} years old. Hello {0}!".format(name, age)
print(formatted_string_with_index) # 输出: My name is Alice and I am 30 years old. Hello Alice!
# 使用命名参数
formatted_string_with_named_args = "My name is {name} and I am {age} years old.".format(name="Bob", age=25)
print(formatted_string_with_named_args) # 输出: My name is Bob and I am 25 years old.
# 格式化数字
value = 123.456789
formatted_number = "The value is {:.2f}".format(value)
print(formatted_number) # 输出: The value is 123.46
str.format()
是 Python 中用于格式化字符串的方法。{}
是占位符,会根据传递的参数顺序或指定的索引、命名参数进行替换。{0}
, {1}
)来指定参数的位置。{name}
, {age}
)来提高代码的可读性。:.2f
)来控制输出的精度。上一篇:python获取字符串长度
下一篇:python drop
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站