# 示例代码:使用 format 方法格式化字符串
# 1. 基本用法
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.
# 解释:在字符串中使用花括号 {} 作为占位符,然后通过 .format() 方法传入相应的变量值。
# 2. 指定位置
formatted_string = "My name is {1} and I am {0} years old.".format(age, name)
print(formatted_string) # 输出: My name is Alice and I am 30 years old.
# 解释:可以通过在花括号内指定索引来控制参数的顺序。
# 3. 使用关键字参数
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.
# 解释:可以使用关键字参数来传递值,并在花括号内引用这些关键字。
# 4. 格式化数字
number = 1234.5678
formatted_string = "The number is {:.2f}".format(number)
print(formatted_string) # 输出: The number is 1234.57
# 解释:可以使用格式说明符(如 {:.2f})来控制数字的显示格式,这里保留两位小数。
上一篇:python进程
下一篇:python wheel
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站