一、基本概念
字符串格式化指的是把一组值按照指定格式进行转换成字符串的过程,常用的方式有“%”和“format()”两种。其中,“%”方式最为常用,而且与C语言的格式化输出功能相似。
格式化字符串的基本语法是:字符串 % 值,其中,字符串中的格式化规则以“%”(模板)字符开头,后面跟着一个或多个格式化字符,表示格式化的方式,最终的结果是将格式化字符和值进行替换。
二、%方式的使用
1、字符串、整数、浮点数、布尔值等的使用
# 字符串格式化
name = "Alice"
print("Hello, %s!" % name)
# 整数格式化
number = 34
print("Your lucky number is %d." % number)
# 浮点数格式化
pi = 3.1415926
print("Pi is approximately %f." % pi)
# 布尔值格式化
flag = False
print("The answer is %s." % flag)
2、大小写、千位分隔符、进制等的使用
# 大小写
s = "world"
print("Hello, %s!" % s.upper())
print("Hello, %s!" % s.capitalize())
print("Hello, %s!" % s.title())
# 千位分隔符
number = 1000000
print("The population of the city is %d." % number)
print("The population of the city is %,d." % number)
# 进制
number = 10
print("The decimal number is %d." % number)
print("The binary number is 0b%02x." % number)
print("The hexadecimal number is 0x%02x." % number)
三、format()方式的使用
1、基本用法
# 使用位置参数
print("The first letter in {0} is {0[0]}.".format("Python"))
# 使用关键字参数
print("The temperature of the {city} is {temp} degrees Celsius.".format(city="Beijing", temp=27))
# 使用属性字段
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Tom", 22)
print("My name is {0.name}, and I am {0.age} years old.".format(p))
2、填充、对齐和宽度
s = "apple"
print("|{:>10}|".format(s)) # 右对齐
print("|{:<10}|".format(s)) # 左对齐
print("|{:^10}|".format(s)) # 居中对齐
# 填充
print("|{:*^10}|".format(s)) # 使用*进行填充
print("|{:*^10.2f}|".format(3.14159)) # 小数点位数为2
# 宽度
print("|{0:10}|{1:5}|".format("Name", "Age"))
print("|{0:10}|{1:5d}|".format("Tom", 22))
print("|{0:10}|{1:5d}|".format("Jerry", 25))
四、f-string方式的使用
f-string是Python3.6新增的一种字符串格式化方式,它简单易用,可以把表达式直接嵌入到字符串中。
1、使用方法
name = "Alice"
print(f"Hello, {name}!")
age = 22
print(f"I am {age} years old.")
pi = 3.1415926
print(f"Pi is approximately {pi:.2f}.")
2、支持运算、函数调用等
print(f"3 + 4 = {3 + 4}.")
print(f"The first letter in {'Python'.upper()} is {'Python'[0]}.")
def greet(name):
return f"Hello, {name}!"
print(greet("Bob"))
五、总结
Python字符串格式化是Python中常用的一种字符串处理方式,可以使用“%”、“format()”和f-string方式进行。其中,“%”方式最为常用,适用于大多数格式化场景,还支持C语言模板字符串和格式化标志;“format()”方式则更加灵活,支持位置参数、关键字参数、属性字段、填充和对齐等功能;而f-string则是Python3.6新增的一种字符串格式化方式,简单易用。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/197302.html
微信扫一扫
支付宝扫一扫