{site_name}

{site_name}

🌜 搜索

Python格式化输出是一种将数据按照指定的格式输出的方法,使得输出结果更加清晰易读

Python 𝄐 0
PYTHON格式化输出f
Python格式化输出是一种将数据按照指定的格式输出的方法,使得输出结果更加清晰易读。格式化输出通常使用字符串格式化操作符或者字符串的format()方法来实现。

以下是两个例子:

1. 字符串格式化操作符

python
# 使用%s格式化字符串
name = 'John'
age = 30
print('My name is %s and I am %d years old.' % (name, age))


输出: My name is John and I am 30 years old.

在上面的例子中,%s 表示一个字符串格式化标识符, name 的值被插入到字符串中的 %s 中; %d 表示一个整数格式化标识符, age 的值被插入到字符串中的 %d 中。

2. 字符串的format()方法

python
# 使用 format() 方法格式化字符串
name = 'John'
age = 30
print('My name is {} and I am {} years old.'.format(name, age))


输出: My name is John and I am 30 years old.

在上面的例子中, {} 表示一个占位符, format() 方法将传递给它的参数依次填充到字符串中的相应位置。

这些只是两个简单的例子,Python格式化输出还有很多其他的用法和技巧,可以通过查看Python官方文档来了解更多细节。