# 示例代码:使用 Python 字符串 format 方法
# 定义变量
name = "Alice"
age = 30
# 使用 format 方法格式化字符串
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.
# 解释说明:
# 1. {} 是占位符,会在 format 方法中被传入的参数替换。
# 2. format 方法可以接受多个参数,按顺序依次替换占位符。
# 3. 还可以使用索引或关键字参数来指定占位符的内容,例如:
formatted_string_with_index = "My name is {0} and I am {1} years old.".format(name, age)
formatted_string_with_keywords = "My name is {n} and I am {a} years old.".format(n=name, a=age)
# 输出结果
print(formatted_string_with_index)
# 输出: My name is Alice and I am 30 years old.
print(formatted_string_with_keywords)
# 输出: My name is Alice and I am 30 years old.
上一篇:python解释器路径
下一篇:python中的字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站