# 示例代码:使用 Python 占位符
# 1. 使用 % 操作符 (旧式格式化)
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string) # 输出: My name is Alice and I am 30 years old.
# 2. 使用 str.format() 方法 (新式格式化)
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.
# 3. 使用 f-string (Python 3.6+ 推荐方式)
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # 输出: My name is Alice and I am 30 years old.
%s
表示字符串占位符,%d
表示整数占位符。这种方式虽然仍然可用,但已经逐渐被更现代的方法取代。{}
作为占位符,并通过 .format()
方法传入参数。这种方式比 %
操作符更灵活,支持更多的格式化选项。f
或 F
,并在字符串中使用 {}
来嵌入表达式。这种方式不仅简洁,而且性能更好。上一篇:python格式化字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站