文章目录
Python提供了多种格式化输出字符串的方法,以下是一些常见的格式化技术及其代码示例:
1. 百分号(%)格式化
这是Python中最早提供的字符串格式化方法之一。
# 输出变量
name = "Alice"
age = 30
greeting = "Hello, %s! You are %d years old." % (name, age)
print(greeting) # 输出: Hello, Alice! You are 30 years old.
%
格式化的高级用法
%
格式化也支持更复杂的格式化选项,比如指定宽度、精度等。
# 指定宽度和精度
number = 3.1415926
formatted_number = "The value of pi is %10.3f" % number
print(formatted_number) # 输出: The value of pi is 3.142
# 左对齐
formatted_number = "The value of pi is %10.3f" % -number
print(formatted_number) # 输出: The value of pi is - 3.142
2. str.format()
方法
str.format()
方法提供了一种灵活的方式来格式化字符串,可以在字符串中使用花括号{}
作为占位符。
#输入变量
name = "Bob"
age = 25
greeting = "Hello, {}! You are {} years old.".format(name, age)
print(greeting) # 输出: Hello, Bob! You are 25 years old.
# 也可以使用索引
greeting = "Hello, {0}! You are {1} years old.".format(name, age)
print(greeting)
# 或者使用关键字
greeting = "Hello, {name}! You are {age} years old.".format(name=name, age=age)
print(greeting)
str.format()
的高级用法
str.format()
方法同样支持复杂的格式化,包括填充、对齐、宽度和精度。
# 使用字典进行格式化
data = {'name': "Dave", 'age': 32}
greeting = "Hello, {name}! You are {age:2d} years old.".format(**data)
print(greeting) # 输出: Hello, Dave! You are 32 years old.
# 填充和对齐
number = 500
formatted_number = "The number is {:05d}".format(number)
print(formatted_number) # 输出: The number is 00500
# 宽度和精度
formatted_number = "The value of pi is {:.2f}".format(3.1415926)
print(formatted_number) # 输出: The value of pi is 3.14
3. f-string
(格式化字符串字面值)
Python 3.6+ 引入了f-string,提供了一种非常简洁和易读的方式来格式化字符串。
# 输出变量
name = "Charlie"
age = 28
greeting = f"Hello, {name}! You are {age} years old."
print(greeting) # 输出: Hello, Charlie! You are 28 years old.
# 直接在花括号内进行表达式计算
score = 88
grade = 'A' if score >= 90 else 'B'
result = f"Your score is {score}, and you get a grade of {grade}."
print(result) # 输出: Your score is 88, and you get a grade of B.
# 输出字符串后在结尾添加制表符/t
print("Hello", end="\t")
print("World")
# 打印:Hello World
4. format()
内置函数
任何数值或对象都有一个format()
方法,可以用来格式化它们。
# 控制小数点后位数
number = 12345.6789
formatted_number = "{:,.2f}".format(number)
print(formatted_number) # 输出: 12,345.68
5. 模板字符串(string.Template
)
Python的string
模块提供了模板字符串功能,它允许你在字符串中使用${}
来插入变量。
# 输入变量
from string import Template
template = Template('Hello, $name! You are $age years old.')
formatted_string = template.substitute(name="Eve", age=35)
print(formatted_string) # 输出: Hello, Eve! You are 35 years old.
依然是元气满满,奋起直追