# 示例代码:使用 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
# 填充和对齐
text = "hello"
formatted_string = "{:>10}".format(text) # 右对齐,总长度为10
print(formatted_string) # 输出: hello
formatted_string = "{:<10}".format(text) # 左对齐,总长度为10
print(formatted_string) # 输出: hello
formatted_string = "{:^10}".format(text) # 居中对齐,总长度为10
print(formatted_string) # 输出: hello
# 填充字符
formatted_string = "{:*^10}".format(text) # 使用 * 填充并居中对齐
print(formatted_string) # 输出: **hello***
# 进制转换
number = 42
formatted_string = "Binary: {0:b}, Octal: {0:o}, Hexadecimal: {0:x}".format(number)
print(formatted_string) # 输出: Binary: 101010, Octal: 52, Hexadecimal: 2a
format 方法是 Python 中用于格式化字符串的一种方式。它允许你将变量插入到字符串中的指定位置。{} 是占位符,format 方法会根据传递的参数依次填充这些占位符。上一篇:python re match
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站