Python-字符串(string)格式化

使用%或是f-string或是format()函数对字符串进行格式化。

1.字符串格式化

1
pass

2.f-string

f-string 是 python3.6 之后版本添加的,称之为字面量格式化字符串,是新的格式化字符串的语法。

f-string 格式化字符串以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去 。

1)简单使用
1
2
3
4
name="world"
say = f"hello {name}"

print(say)

输出如下:

1
'hello world'
2)表达式求值与函数调用
1
2
3
numCal = f"num calculate result is {214*22}."
funCall = f"A is {ord('A')}."
print(numcal,funCall,sep="\n")

输出如下:

1
2
num calculate result is 4708.
A is 65.
3)lambda表达式

lambda表达式的 : 会被f-string误认为是表达式与格式描述符之间的分隔符,为避免歧义,需要将lambda表达式置于括号 () 内。

1
2
twoSquare = f"two's square is {(lambda x:x*x)(2)}."
print(twoSquare)

输出如下:

1
two's square is 4.

参考链接:

https://blog.csdn.net/sunxb10/article/details/81036693

https://www.runoob.com/python3/python3-string.html

3.format()函数

1)使用位置参数
1
2
3
4
string1 = "{} am {}".format("I","the best")#按照默认顺序,不指定位置
string2 = "{0} am {1}.{0} am proud.".format("I","the best")#设置指定位置,可以多次使用

print(string1,string2,sep="\n")

输出如下:

1
2
I am the best
I am the best.I am proud.
2)使用关键字参数
1
2
string = "I like {country}.".format(country = "China")
print(string)

输出如下:

1
I like China.
3) 填充与格式化
1
2
3
4
5
string1 = "{log:*>20}".format(log="error")#右对齐
string2 = "{log:*<20}".format(log="info")#左对齐
string3 = "{0:*^20}".format("logging")#居中对齐

print(string1,string2,string3,sep="\n")

输出如下:

1
2
3
***************error
info****************
******logging*******
4) 精度
1
2
3
4
5
6
7
8
string1 = "{num:.2f}".format(num=4/3)#保留小数点后两位
string2 = "{0:+.2f}".format(4/3)#带符号保留小数点后两位
string3 = "{0:.0f}".format(4/3)#不带小数
string4 = "{0:.2%}".format(4/3)#百分比格式
string5 = "{0:.3e}".format(100000000)#科学计数法格式
string6 = "{0:,}".format(1622110141)#千分位格式化

print(string1,string2,string3,string4,string5,string6,sep="\n")

输出如下:

1
2
3
4
5
6
1.33
+1.33
1
133.33%
1.000e+08
1,622,110,141
5)进制
1
2
3
4
5
6
7
8
string1 = "{0:b}".format(10)#二进制
string2 = "{0:d}".format(10)#十进制
string3 = "{0:o}".format(10)#八进制
string4 = "{0:x}".format(10)#16进制
string5 = "{0:#x}".format(10)#16进制,前置0
string6 = "{0:#X}".format(10)#16进制,前置0,字母大写

print(string1,string2,string3,string4,string5,string6,sep="\n")

输出如下:

1
2
3
4
5
6
1010
10
12
a
0xa
0XA
6)使用索引
1
2
listTemp = ["CPlusPlus","Java","MySQL","Python"]
print("I like {0[0]} , I also love {0[1]} !".format(listTemp))

输出如下:

1
I like CPlusPlus , I also love Java !
7)通过字典格式化
1
2
map = {"name":"Yebin","language":"Python"}
print("My name is {name},I love {language}.".format(**map))

输出如下:

1
My name is Yebin,I love Python.
8)通过元组格式化
1
2
tupleTemp = ("Yes","No")
print("{},I Love you.{},I hate you.".format(*tupleTemp))

输出如下:

1
Yes,I Love you.No,I hate you.

参考链接:

https://www.runoob.com/python3/python3-string.html

https://www.cnblogs.com/jonm/p/8280968.html

https://baijiahao.baidu.com/s?id=1618722730278133164&wfr=spider&for=pc