Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python格式化输出

作者:满身补丁   发布日期:2025-09-27   浏览:28

# 示例代码: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关键字

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站