# 示例代码:使用 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 {1} and I am {0} years old.".format(age, name)
print(formatted_string_with_index) # 输出: My name is Alice and I am 30 years old.
# 使用关键字参数
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.
# 格式化数字
formatted_number = "The value of pi is approximately {:.2f}".format(3.14159)
print(formatted_number) # 输出: The value of pi is approximately 3.14
# 对齐文本
left_aligned = "{:<10}".format("left")
right_aligned = "{:>10}".format("right")
centered = "{:^10}".format("center")
print(left_aligned, right_aligned, centered) # 输出: left right center
# 填充字符
padded_number = "{:#<10}".format(7)
print(padded_number) # 输出: 7#########
# 使用变量作为格式化参数
width = 10
precision = 4
value = 123.456789
formatted_value = "{:{width}.{precision}f}".format(value, width=width, precision=precision)
print(formatted_value) # 输出: 123.4568
format
方法是 Python 中用于字符串格式化的强大工具。上一篇:python 数组
下一篇:python 爬虫
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站