在Python中,字符串格式化是一种将变量或值插入到字符串中的方法,以创建具有特定格式的字符串。有多种方式可以在Python中进行字符串格式化,以下是其中一些常见的方法。
Python 中的字符串格式化
在 Python 中执行字符串格式化有五种不同的方法
- 使用 % 运算符进行格式化。
- 使用 format() 字符串方法进行格式化。
- 使用f-字符串(f-strings)进行格式化。
- 使用字符串模板类进行格式化
- 使用 center() 字符串方法格式化。
使用 % 运算符格式化字符串
这是一种古老的字符串格式化方法,使用百分号占位符将变量插入字符串中。
例子:
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
输出:
My name is Alice and I am 30 years old.
使用%运算符注入多个字符串
这里我们使用 % 运算符插入多个字符串。
x = 'looked'
print("Misha %s and %s around"%('walked',x))
输出:
Misha walked and looked around.
Python 中使用 % 运算符的精度处理
浮点数使用格式%a.bf。这里,a是字符串中出现的最小位数;如果整个数字没有这么多数字,则可能会用空格填充这些数字。与此接近的是,bf表示小数点后要显示多少位。
在此代码中,字符串“The value of pi is: %5.4f”包含格式说明符 %5.4f。%5.4f 格式说明符用于格式化最小宽度为 5、精度为 4 位小数的浮点数。
print('The value of pi is: %5.4f' %(3.141592))
输出:
The value of pi is: 3.1416
多种格式转换类型
在给定的代码中,格式化字符串使用 %d,%f 转换为整数和浮点数。
variable = 12
string = "Variable as integer = %d \n\
Variable as float = %f" %(variable, variable)
print (string)
输出:
Variable as integer = 12
Variable as float = 12.000000
使用 format() 方法进行格式化
Python3 引入了Format() 方法,用于更有效地处理复杂的字符串格式。格式化程序的工作原理是将一对大括号 { } 定义的一个或多个替换字段和占位符放入字符串中并调用 str.format ()。
使用 format() 方法格式化字符串
name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
输出:
My name is Bob and I am 25 years old.
基于索引的插入
在此代码中,字符串“{2} {1} {0}”中使用带有索引的花括号 {} 来指示相应值的放置位置。
print('{2} {1} {0}'.format('directions','the', 'Read'))
输出:
Read the directions.
通过分配关键字插入对象
在此代码中,在字符串“a: {a}, b: {b}, c: {c}”内使用带命名占位符 ({a}, {b}, {c}) 的花括号 {} 来指示相应命名参数的放置位置。
print('a: {a}, b: {b}, c: {c}'.format(a = 1,b = 'Two',c = 12.3))
输出:
a: 1, b: Two, c: 12.3
使用 .format() 方法实现浮点精度
语法: {[索引]:[宽度][.精度][类型]}
该类型可以与格式代码一起使用:
- ‘d’代表整数
- ‘f’表示浮点数
- ‘b’表示二进制数
- ‘o’表示八进制数
- ‘x’表示八进制十六进制数
- ‘s’代表字符串
- ‘e’表示指数格式的浮点数
例子:
两个代码都在进行字符串格式化。第一个字符串使用 ‘%’ 进行格式化,第二个字符串使用 .format() 进行格式化。
print('The value of pi is: %1.5f' %3.141592)
print('The value of pi is: {0:1.5f}'.format(3.141592))
输出:
The value of pi is: 3.14159
The value of pi is: 3.14159
使用f-字符串进行格式化
要在 Python 中创建 f 字符串,请在字符串前添加字母“f”。字符串本身的格式化方式与 str 的格式化方式大致相同。格式()。F 字符串提供了一种简洁便捷的方法,可将 Python 表达式嵌入到字符串文字中进行格式化。
使用 F 字符串格式化字符串
在此代码中,f 字符串f“My name is {name}.” 用于将 name 变量的值插入到字符串中。
name = 'Ele'
print(f"My name is {name}.")
输出:
My name is Ele
使用 F 字符串的算术运算
在此代码中,f 字符串f“He said his age is {2 * (a + b)}。” 用于将表达式 2 * (a + b) 的结果插值到字符串中。
a = 5
b = 10
print(f"He said his age is {2 * (a + b)}.")
输出:
He said his age is 30.
我们还可以在f 字符串格式中使用lambda表达式。
使用 F 字符串的 Lambda 表达式
在此代码中,使用 lambda x: x*2 定义匿名 lambda 函数。此 lambda 函数接受参数 x 并返回其双精度值。
print(f"He said his age is {(lambda x: x*2)(3)}")
输出:
He said his age is 6.
f-String 方法中的浮点精度
在此代码中,使用 f 字符串格式将 num 变量的值插入到字符串中。
语法:{值:{宽度}.{精度}}
num = 3.14159
print(f"The value of pi is: {num:{1}.{5}}")
输出:
The value of pi is: 3.1416
Python 字符串模板进行格式化
Python还提供了string.Template类,它使用 $ 符号作为占位符,并通过substitute方法将值插入占位符。
此代码从 string 模块导入 Template 类。Template 类允许我们创建带有可以用实际值替换的占位符的模板字符串。这里我们用值 n1 和 n2 替换字符串 n 中的 n3 和 n4。
from string import Template
n1 = 'Hello'
n2 = 'Jkhxw for Geeks'
# 创建一个模板字符串,并指定占位符为$n3和$n4
n = Template('$n3 ! This is $n4.')
# 使用substitute方法将变量值插入模板字符串中
print(n.substitute(n3=n1, n4=n2))
输出:
Hello ! This is Jkhxw for Geeks.
Python String center() 方法进行格式化
center() 方法是Python的 str 类 中的内置方法,它返回一个在指定宽度的字符串中居中的新字符串。
使用 center() 方法格式化字符串
此代码返回一个在左侧和右侧填充空格的新字符串。在这个示例中,原始字符串 “Jkhxw For Geeks!” 被居中对齐,并用空格填充左右两侧,以使总宽度为 30 个字符。
string = "Jkhxw For Geeks!"
width = 30
centered_string = string.center(width)
print(centered_string)
输出:
Jkhxw For Geeks!
字符串格式:% vs .format vs f 字符串
f 字符串比% 格式化和str.format()更快更好。f 字符串表达式在运行时计算,我们还可以使用非常简单的语法将表达式嵌入到 f 字符串中。大括号内的表达式在运行时计算,然后与 f 字符串的字符串部分放在一起,然后返回最终字符串。
注意:如果字符串是用户提供的字符串,请使用模板字符串,否则如果您使用的是 Python 3.6+,则使用 f-Strings。