# 示例代码:Python格式化输出
# 1. 使用 % 操作符进行格式化输出
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age))
# 解释:'%s' 和 '%d' 是占位符,分别表示字符串和整数。后面的元组提供具体的值。
# 2. 使用 str.format() 方法进行格式化输出
print("My name is {} and I am {} years old.".format(name, age))
# 解释:花括号 {} 是占位符,format() 方法根据顺序填充这些占位符。
# 3. 使用 f-string(Python 3.6+)进行格式化输出
print(f"My name is {name} and I am {age} years old.")
# 解释:f-string 在字符串前加 'f' 或 'F',允许在字符串中直接嵌入表达式。
# 4. 格式化浮点数
pi = 3.1415926
print("Pi is approximately %.2f" % pi) # 使用 % 操作符
print("Pi is approximately {:.2f}".format(pi)) # 使用 str.format()
print(f"Pi is approximately {pi:.2f}") # 使用 f-string
# 解释:'.2f' 表示保留两位小数。
上一篇:python websocket
下一篇:python关键字
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站