# 示例代码:使用 .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_keywords = "My name is {name} and I am {age} years old.".format(name="Bob", age=25)
print(formatted_string_with_keywords) # 输出: My name is Bob and I am 25 years old.
# 格式化数字
pi = 3.141592653589793
formatted_pi = "The value of pi is approximately {:.2f}".format(pi)
print(formatted_pi) # 输出: The value of pi is approximately 3.14
# 对齐和填充
formatted_text = "{:<10}|{:>10}".format("left", "right")
print(formatted_text) # 输出: left | right
.format() 方法用于将值插入到字符串中的占位符 {} 中。上一篇:python print(f)
下一篇:python init
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站