# 示例代码:使用 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.
# 2. 指定位置参数
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
# 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
# 5. 对齐和填充
formatted_string = "{:<10}|{:>10}".format("left", "right")
print(formatted_string) # 输出: left | right
formatted_string = "{:^10}".format("center")
print(formatted_string) # 输出: center
formatted_string = "{:*^10}".format("center")
print(formatted_string) # 输出: **center**
# 6. 使用变量作为格式化参数
width = 10
precision = 4
value = 1234.5678
formatted_string = "The value is {:{width}.{precision}f}".format(value, width=width, precision=precision)
print(formatted_string) # 输出: The value is 1234.5678
format
方法是 Python 中用于字符串格式化的强大工具。{}
是占位符,{}
中的内容可以指定索引、变量名或格式化选项。上一篇:python numba
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站