# 示例代码:使用 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 = "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.
# 使用关键字参数
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.
# 格式化数字
formatted_string = "The value of pi is approximately {:.2f}.".format(3.14159)
print(formatted_string) # 输出: The value of pi is approximately 3.14.
# 对齐和填充
formatted_string = "{:>10}".format("hello") # 右对齐,总宽度为10
print(formatted_string) # 输出: hello
formatted_string = "{:<10}".format("hello") # 左对齐,总宽度为10
print(formatted_string) # 输出: hello
formatted_string = "{:^10}".format("hello") # 居中对齐,总宽度为10
print(formatted_string) # 输出: hello
formatted_string = "{:*^10}".format("hello") # 居中对齐,用 * 填充,总宽度为10
print(formatted_string) # 输出: **hello***
# 使用变量作为格式化参数
width = 10
formatted_string = "{:{width}}".format("hello", width=width)
print(formatted_string) # 输出: hello
format 函数用于将指定的值插入到字符串中的占位符 {} 中。{}),也可以包含索引(如 {0}, {1})或关键字(如 {name}, {age})。下一篇:python mkdir
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站