# 示例代码:使用 Python 的 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_position = "I am {1} years old and my name is {0}.".format(name, age)
print(formatted_string_with_position) # 输出: I am 30 years old and my name is Alice.
# 使用关键字参数
formatted_string_with_keywords = "Hello, my name is {name} and I am {age} years old.".format(name="Bob", age=25)
print(formatted_string_with_keywords) # 输出: Hello, my name is Bob and I am 25 years old.
# 格式化数字
pi = 3.141592653589793
formatted_pi = "The value of pi is approximately {:.2f}".format(pi)
print(formatted_pi) # 输出: The value of pi is approximately 3.14
# 对齐文本
text = "hello"
formatted_text = "{:>10}".format(text) # 右对齐,总长度为10
print(formatted_text) # 输出: hello
format()
方法用于格式化字符串。它允许你将变量插入到字符串中,使字符串更具动态性和可读性。{}
是占位符,format()
方法会根据传入的参数依次替换这些占位符。{0}
, {1}
)或关键字(如 {name}
, {age}
)来控制参数的顺序和内容。.2f
表示保留两位小数的浮点数格式。{:>10}
表示右对齐,总长度为10个字符。上一篇:print在python中用法
下一篇:python字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站