# 示例代码:使用 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.
# 格式化数字
pi = 3.141592653589793
formatted_string = "The value of pi is approximately {:.2f}".format(pi)
print(formatted_string) # 输出: The value of pi is approximately 3.14
# 对齐和填充
formatted_string = "{:<10} | {:^10} | {:>10}".format("left", "center", "right")
print(formatted_string) # 输出: left | center | right
format
函数用于将指定的值插入到字符串中。{}
是占位符,表示将在此处插入值。:.2f
表示保留两位小数。<
, ^
, >
分别表示左对齐、居中对齐和右对齐。上一篇:python打开文件
下一篇:python for 循环
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站