【积累】Python中字符串格式化的三种方法
详细介绍Python中字符串格式化的 "fstring" ,".format()" 和 "%" 三种方法
Python中字符串格式化的三种方法
在Python中,字符串格式化是一种将变量插入到字符串中的方法。主要有三种常用的方法来进行字符串格式化:
- 使用f-strings(需要Python 3.6+)
- 使用
str.format()
- 使用旧式的
%
格式化
下面详细介绍这三种方法,并通过例子来展示它们的使用。
1. 使用f-strings(Python 3.6+)
f-strings(格式化字符串字面值)是Python 3.6引入的一种字符串格式化方法。它通过在字符串前加上字母f
,然后在字符串中使用花括号{}
包裹变量或表达式来实现格式化。
- 优点:写起来简单,速度快
- 缺点:只支持python 3.6以上的版本,但是似乎现在大多代码都是基于python 3.6+写的
✨个人感觉这种方法最好用✨
基本示例
将变量直接嵌入字符串中。
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 30 years old.
解释:在字符串前加上字母f
,并在字符串内部使用花括号{}
包裹变量name
和age
,Python会自动将变量的值嵌入到字符串中。
小数格式化
格式化小数,指定小数点后的位数。
pi = 3.1415926535
print(f"Pi rounded to 2 decimal places: {pi:.2f}")
# Output: Pi rounded to 2 decimal places: 3.14
tax_rate = 0.07
amount = 100
tax = amount * tax_rate
print(f"Tax amount: {tax:.2f}")
# Output: Tax amount: 7.00
temperature = 23.567
print(f"Current temperature: {temperature:.1f}°C")
# Output: Current temperature: 23.6°C
解释:在花括号内使用格式规范符号,如.2f
表示保留两位小数,.1f
表示保留一位小数。
百分数格式化
将小数格式化为百分数。
percentage = 0.85
print(f"Success rate: {percentage:.2%}")
# Output: Success rate: 85.00%
growth_rate = 0.034
print(f"Growth rate: {growth_rate:.1%}")
# Output: Growth rate: 3.4%
discount = 0.15
print(f"Discount: {discount:.0%}")
# Output: Discount: 15%
解释:在花括号内使用格式规范符号:.2%
、:.1%
等,将小数转换为百分数形式,并指定小数点后的位数。
与函数结合使用
可以在f-strings中调用函数来处理变量。
name = "alice"
print(f"My name in uppercase is {name.upper()}")
# Output: My name in uppercase is ALICE
def square(n):
return n * n
num = 4
print(f"The square of {num} is {square(num)}")
# Output: The square of 4 is 16
text = "python programming"
print(f"Title case: {text.title()}")
# Output: Title case: Python Programming
解释:在花括号内可以直接调用函数,如name.upper()
将名字转换为大写,square(num)
计算数字的平方。
整数格式化
格式化整数,添加逗号作为千位分隔符。
number = 123456789
print(f"Formatted number with commas: {number:,}")
# Output: Formatted number with commas: 123,456,789
large_number = 9876543210
print(f"Formatted large number: {large_number:,}")
# Output: Formatted large number: 9,876,543,210
small_number = 1234
print(f"Formatted small number: {small_number:,}")
# Output: Formatted small number: 1,234
解释:在花括号内使用格式规范符号:,
,将整数格式化为带有千位分隔符的字符串。
多个变量
在一个字符串中嵌入多个变量。
first_name = "Alice"
last_name = "Smith"
age = 30
print(f"My name is {first_name} {last_name} and I am {age} years old.")
# Output: My name is Alice Smith and I am 30 years old.
city = "New York"
country = "USA"
population = 8419000
print(f"{city} is a city in {country} with a population of {population}.")
# Output: New York is a city in USA with a population of 8419000.
product = "laptop"
price = 999.99
quantity = 3
print(f"The price of one {product} is ${price:.2f}. Total cost for {quantity} is ${price * quantity:.2f}.")
# Output: The price of one laptop is $999.99. Total cost for 3 is $2999.97.
解释:可以在一个f-string中嵌入多个变量,使用多个花括号{}
包裹变量或表达式。
嵌套表达式
在f-strings中直接使用表达式进行计算。
x = 5
print(f"Five squared is {x**2}")
# Output: Five squared is 25
a = 2
b = 3
print(f"The result of {a} to the power of {b} is {a**b}")
# Output: The result of 2 to the power of 3 is 8
radius = 7
print(f"The area of a circle with radius {radius} is {3.14 * (radius**2):.2f}")
# Output: The area of a circle with radius 7 is 153.86
解释:在花括号内可以直接使用表达式进行计算,如x**2
计算平方,a**b
计算幂,3.14 * (radius**2)
计算圆的面积。
日期格式化
使用格式化代码将日期格式化为字符串。
from datetime import datetime
now = datetime.now()
print(f"Current date and time: {now:%Y-%m-%d %H:%M:%S}")
# Output: Current date and time: 2024-08-02 14:20:05
birthday = datetime(1990, 12, 25)
print(f"Birthday: {birthday:%A, %B %d, %Y}")
# Output: Birthday: Tuesday, December 25, 1990
start_date = datetime(2022, 1, 1)
end_date = datetime(2022, 12, 31)
print(f"Start date: {start_date:%Y-%m-%d}, End date: {end_date:%Y-%m-%d}")
# Output: Start date: 2022-01-01, End date: 2022-12-31
解释:在花括号内使用格式规范符号,如%Y
表示四位数年份,%m
表示两位数月份,%d
表示两位数日期,%H:%M:%S
表示24小时制时间。
对齐文本和宽度控制
控制字符串的对齐方式和宽度。
width = 10
print(f"{'left':<{width}} | {'center':^{width}} | {'right':>{width}}")
# Output:
# left | center | right
word1 = "apple"
word2 = "banana"
print(f"{word1:<10} {word2:<10}")
# Output:
# apple banana
title = "Report"
print(f"{title:^30}")
# Output: Report
解释:在花括号内使用格式规范符号控制对齐方式和宽度,如:<
表示左对齐,:^
表示居中对齐,:>
表示右对齐,后面跟随宽度数值。
结合字典使用
通过字典键值对进行格式化。
person = {'name': 'Alice', 'age': 30}
print(f"My name is {person['name']} and I am {person['age']} years old.")
# Output: My name is Alice and I am 30 years old.
product_info = {"name": "Laptop", "price": 999.99}
print(f"The {product_info['name']} costs ${product_info['price']:.2f}.")
# Output: The Laptop costs $999.99.
stats = {"games": 12, "wins": 9, "losses": 3}
print(f
"Games: {stats['games']}, Wins: {stats['wins']}, Losses: {stats['losses']}")
# Output: Games: 12, Wins: 9, Losses: 3
解释:可以通过字典键值对进行格式化,在花括号内使用字典的键访问相应的值。
结合列表使用
通过列表索引进行格式化。
fruits = ["apple", "banana", "cherry"]
print(f"My favorite fruits are: {fruits[0]}, {fruits[1]}, and {fruits[2]}.")
# Output: My favorite fruits are: apple, banana, and cherry.
scores = [85, 92, 78]
print(f"Math: {scores[0]}, Science: {scores[1]}, English: {scores[2]}")
# Output: Math: 85, Science: 92, English: 78
coordinates = [10.5, 20.3]
print(f"Latitude: {coordinates[0]}, Longitude: {coordinates[1]}")
# Output: Latitude: 10.5, Longitude: 20.3
解释:可以通过列表索引进行格式化,在花括号内使用列表的索引访问相应的值。
使用对象属性
通过对象的属性进行格式化。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
print(f"My name is {person.name} and I am {person.age} years old.")
# Output: My name is Alice and I am 30 years old.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
product = Product("Laptop", 999.99)
print(f"The {product.name} costs ${product.price:.2f}.")
# Output: The Laptop costs $999.99.
class Student:
def __init__(self, first_name, last_name, grade):
self.first_name = first_name
self.last_name = last_name
self.grade = grade
student = Student("John", "Doe", "A")
print(f"Student: {student.first_name} {student.last_name}, Grade: {student.grade}")
# Output: Student: John Doe, Grade: A
解释:可以通过对象的属性进行格式化,在花括号内使用对象的属性访问相应的值。
带有条件表达式
在f-strings中使用条件表达式。
is_logged_in = True
print(f"You are {'logged in' if is_logged_in else 'not logged in'}.")
# Output: You are logged in.
temperature = 35
print(f"The weather is {'hot' if temperature > 30 else 'cold'}.")
# Output: The weather is hot.
score = 85
print(f"You {'passed' if score >= 60 else 'failed'} the exam.")
# Output: You passed the exam.
解释:在花括号内可以使用条件表达式,根据条件选择输出的内容。
转义大括号
显示大括号时使用双大括号{{
和}}
。
value = 10
print(f"Value in braces: {{value}}")
# Output: Value in braces: {value}
config = {"path": "/usr/local/bin", "version": "1.2.3"}
print(f"Config: path={{config['path']}}, version={{config['version']}}")
# Output: Config: path={config['path']}, version={config['version']}
matrix = [[1, 2], [3, 4]]
print(f"Matrix: {{ {matrix[0][0]}, {matrix[0][1]} }, { {matrix[1][0]}, {matrix[1][1]} }}")
# Output: Matrix: { 1, 2 }, { 3, 4 }
解释:当需要在字符串中显示大括号时,使用双大括号{{
和}}
进行转义。
2. 使用str.format()
str.format()
方法是Python 3引入的字符串格式化方法。它通过在字符串中使用花括号{}
来占位,并在后面调用.format()
方法来传递变量。
- 优点:灵活度相对高一点,兼容python2.7和3.x
- 缺点:写起来麻烦,特别是有多个变量的时候
基本示例
使用str.format()
将变量插入到字符串中。
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Alice and I am 30 years old.
city = "Paris"
country = "France"
print("The capital of {} is {}.".format(country, city))
# Output: The capital of France is Paris.
product = "Notebook"
price = 12.99
print("The price of one {} is ${}.".format(product, price))
# Output: The price of one Notebook is $12.99.
解释:在字符串中使用花括号{}
作为占位符,然后在.format()
方法中传递相应的变量,Python会自动将变量的值嵌入到字符串中。
小数格式化
使用str.format()
格式化小数。
pi = 3.1415926535
print("Pi rounded to 2 decimal places: {:.2f}".format(pi))
# Output: Pi rounded to 2 decimal places: 3.14
tax_rate = 0.075
amount = 200
tax = amount * tax_rate
print("Tax amount: {:.2f}".format(tax))
# Output: Tax amount: 15.00
distance = 150.4567
print("Distance: {:.1f} km".format(distance))
# Output: Distance: 150.5 km
解释:在花括号内使用格式规范符号,如.2f
表示保留两位小数,.1f
表示保留一位小数。
百分数格式化
将小数格式化为百分数。
percentage = 0.85
print("Success rate: {:.2%}".format(percentage))
# Output: Success rate: 85.00%
growth_rate = 0.034
print("Growth rate: {:.1%}".format(growth_rate))
# Output: Growth rate: 3.4%
discount = 0.15
print("Discount: {:.0%}".format(discount))
# Output: Discount: 15%
解释:在花括号内使用格式规范符号:.2%
、:.1%
等,将小数转换为百分数形式,并指定小数点后的位数。
与函数结合使用
在str.format()
中调用函数。
name = "alice"
print("My name in uppercase is {}".format(name.upper()))
# Output: My name in uppercase is ALICE
def cube(n):
return n * n * n
num = 3
print("The cube of {} is {}".format(num, cube(num)))
# Output: The cube of 3 is 27
text = "learning python"
print("Title case: {}".format(text.title()))
# Output: Title case: Learning Python
解释:在花括号内可以直接调用函数,如name.upper()
将名字转换为大写,cube(num)
计算数字的立方。
整数格式化
使用str.format()
格式化整数,添加逗号作为千位分隔符。
number = 123456789
print("Formatted number with commas: {:,}".format(number))
# Output: Formatted number with commas: 123,456,789
large_number = 9876543210
print("Formatted large number: {:,}".format(large_number))
# Output: Formatted large number: 9,876,543,210
small_number = 5678
print("Formatted small number: {:,}".format(small_number))
# Output: Formatted small number: 5,678
解释:在花括号内使用格式规范符号:,
,将整数格式化为带有千位分隔符的字符串。
多个变量
在一个字符串中嵌入多个变量。
first_name = "Alice"
last_name = "Smith"
age = 30
print("My name is {} {} and I am {} years old.".format(first_name, last_name, age))
# Output: My name is Alice Smith and I am 30 years old.
city = "Los Angeles"
state = "California"
population = 3970000
print("{} is a city in {} with a population of {:,}.".format(city, state, population))
# Output: Los Angeles is a city in California with a population of 3,970,000.
item = "book"
price = 19.99
quantity = 4
print("The price of one {} is ${:.2f}. Total cost for {} is ${:.2f}.".format(item, price, quantity, price * quantity))
# Output: The price of one book is $19.
99. Total cost for 4 is $79.96.
解释:可以在一个str.format()
方法中传递多个变量,使用多个花括号{}
包裹变量或表达式。
嵌套表达式
在str.format()
中直接使用表达式进行计算。
x = 5
print("Five squared is {}".format(x**2))
# Output: Five squared is 25
a = 3
b = 4
print("The result of {} to the power of {} is {}".format(a, b, a**b))
# Output: The result of 3 to the power of 4 is 81
radius = 10
print("The area of a circle with radius {} is {:.2f}".format(radius, 3.14 * (radius**2)))
# Output: The area of a circle with radius 10 is 314.00
解释:在花括号内可以直接使用表达式进行计算,如x**2
计算平方,a**b
计算幂,3.14 * (radius**2)
计算圆的面积。
日期格式化
使用格式化代码将日期格式化为字符串。
from datetime import datetime
now = datetime.now()
print("Current date and time: {:%Y-%m-%d %H:%M:%S}".format(now))
# Output: Current date and time: 2024-08-02 14:20:05
birthday = datetime(1995, 5, 15)
print("Birthday: {:%A, %B %d, %Y}".format(birthday))
# Output: Birthday: Monday, May 15, 1995
start_date = datetime(2023, 1, 1)
end_date = datetime(2023, 12, 31)
print("Start date: {:%Y-%m-%d}, End date: {:%Y-%m-%d}".format(start_date, end_date))
# Output: Start date: 2023-01-01, End date: 2023-12-31
解释:在花括号内使用格式规范符号,如%Y
表示四位数年份,%m
表示两位数月份,%d
表示两位数日期,%H:%M:%S
表示24小时制时间。
指定位置参数
在str.format()
中指定位置参数。
name = "Alice"
age = 30
print("My name is {0} and I am {1} years old. {0} is a developer.".format(name, age))
# Output: My name is Alice and I am 30 years old. Alice is a developer.
city = "Paris"
country = "France"
print("{1} is the capital of {0}. {0} is a beautiful country.".format(country, city))
# Output: Paris is the capital of France. France is a beautiful country.
item = "chair"
price = 49.99
print("The price of a {0} is ${1:.2f}. I bought a {0} yesterday.".format(item, price))
# Output: The price of a chair is $49.99. I bought a chair yesterday.
解释:在花括号内使用数字指定位置参数,可以重复使用相同的变量。
命名参数
在str.format()
中使用命名参数。
print("My name is {name} and I am {age} years old.".format(name="Alice", age=30))
# Output: My name is Alice and I am 30 years old.
print("{city} is the capital of {country}.".format(city="Paris", country="France"))
# Output: Paris is the capital of France.
print("The {product} costs ${price:.2f}.".format(product="Laptop", price=999.99))
# Output: The Laptop costs $999.99.
解释:在.format()
方法中使用命名参数,可以通过名字传递参数,增加代码的可读性。
3. 使用旧式的%
格式化
旧式的%
格式化方法在Python 2中很流行,但在Python 3中已经不推荐使用这种方法(但还是有非常多人用🤣)。通过在字符串中使用%
符号来插入变量。
- 优点:适用于维护旧代码
- 缺点:写起来相对麻烦,并且灵活性也不如其他两种
基本示例
使用%
操作符将变量插入到字符串中。
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age))
# Output: My name is Alice and I am 30 years old.
city = "London"
country = "UK"
print("The capital of %s is %s." % (country, city))
# Output: The capital of UK is London.
product = "Phone"
price = 699.99
print("The price of one %s is $%.2f." % (product, price))
# Output: The price of one Phone is $699.99.
解释:在字符串中使用%
符号作为占位符,并在后面的元组中传递相应的变量,Python会自动将变量的值嵌入到字符串中。%s
表示字符串,%d
表示整数,%.2f
表示保留两位小数的浮点数。
小数格式化
使用%
操作符格式化小数。
pi = 3.1415926535
print("Pi rounded to 2 decimal places: %.2f" % pi)
# Output: Pi rounded to 2 decimal places: 3.14
tax_rate = 0.075
amount = 150
tax = amount * tax_rate
print("Tax amount: %.2f" % tax)
# Output: Tax amount: 11.25
temperature = 25.678
print("Current temperature: %.1f°C" % temperature)
# Output: Current temperature: 25.7°C
解释:在字符串中使用%.2f
表示保留两位小数的浮点数,%.1f
表示保留一位小数的浮点数。
百分数格式化
将小数格式化为百分数。
percentage = 0.85
print("Success rate: %.2f%%" % (percentage * 100))
# Output: Success rate: 85.00%
growth_rate = 0.045
print("Growth rate: %.1f%%" % (growth_rate * 100))
# Output: Growth rate: 4.5%
discount = 0.2
print("Discount: %.0f%%" % (discount * 100))
# Output: Discount: 20%
解释:在字符串中使用%.2f%%
表示保留两位小数的百分数,%.1f%%
表示保留一位小数的百分数,%.0f%%
表示保留整数的百分数。注意,百分号需要转义,即使用两个百分号%%
。
与函数结合使用
在%
操作符中调用函数。
name = "alice"
print("My name in uppercase is %s" % name.upper())
# Output: My name in uppercase is ALICE
def double(n):
return n * 2
num = 5
print("The double of %d is %d" % (num, double(num)))
# Output: The double of 5 is 10
text = "hello world"
print("Uppercase: %s" % text.upper())
# Output: Uppercase: HELLO WORLD
解释:在字符串中可以直接调用函数,如name.upper()
将名字转换为大写,double(num)
计算数字的两倍。
整数格式化
使用%
操作符格式化整数,添加逗号作为千位分隔符。
number = 123456789
print("Formatted number with commas: %,d" % number)
# Output: Formatted number with commas: 123,456,789
large_number = 9876543210
print("Formatted large number: %,d" % large_number)
# Output: Formatted large number: 9,876,543,210
small_number = 4321
print("Formatted small number: %,d" % small_number)
# Output: Formatted small number: 4,321
解释:在字符串中使用%,d
,将整数格式化为带有千位分隔符的字符串。
多个变量格式化
在一个字符串中嵌入多个变量。
first_name = "Alice"
last_name = "Smith"
age = 30
height = 5.6
print("Name: %s %s, Age: %d, Height: %.1f" % (first_name, last_name, age, height))
# Output: Name: Alice Smith, Age: 30, Height: 5.6
city = "Tokyo"
country = "Japan"
population = 13929286
print("City: %s, Country:
%s, Population: %,d" % (city, country, population))
# Output: City: Tokyo, Country: Japan, Population: 13,929,286
item = "pen"
price = 1.5
quantity = 10
print("Item: %s, Price: $%.2f, Quantity: %d, Total: $%.2f" % (item, price, quantity, price * quantity))
# Output: Item: pen, Price: $1.50, Quantity: 10, Total: $15.00
解释:可以在一个字符串中使用多个%
占位符,并在后面的元组中传递相应的变量。
嵌套表达式
在%
操作符中直接使用表达式进行计算。
x = 5
print("Five squared is %d" % (x**2))
# Output: Five squared is 25
a = 2
b = 8
print("The result of %d to the power of %d is %d" % (a, b, a**b))
# Output: The result of 2 to the power of 8 is 256
radius = 6
print("The area of a circle with radius %d is %.2f" % (radius, 3.14 * (radius**2)))
# Output: The area of a circle with radius 6 is 113.04
解释:在字符串中的元组中可以直接使用表达式进行计算,如x**2
计算平方,a**b
计算幂,3.14 * (radius**2)
计算圆的面积。
日期格式化
使用格式化代码将日期格式化为字符串。
from datetime import datetime
now = datetime.now()
print("Current date and time: %s" % now.strftime("%Y-%m-%d %H:%M:%S"))
# Output: Current date and time: 2024-08-02 14:20:05
birthday = datetime(1985, 10, 22)
print("Birthday: %s" % birthday.strftime("%A, %B %d, %Y"))
# Output: Birthday: Tuesday, October 22, 1985
start_date = datetime(2021, 7, 1)
end_date = datetime(2021, 12, 31)
print("Start date: %s, End date: %s" % (start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d")))
# Output: Start date: 2021-07-01, End date: 2021-12-31
解释:使用datetime
模块中的strftime
方法,将日期格式化为字符串,在格式化代码中使用%Y
表示四位数年份,%m
表示两位数月份,%d
表示两位数日期,%H:%M:%S
表示24小时制时间。
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)