字符串是序列的一种,因此标准序列操作都适用于字符串,但字符串是不可变的。因此任何元素赋值和切片赋值都是非法的。
1 设置字符串格式
1.1 精简版
使用字符串格式设置运算符%,其左边指定一个字符串,右边指定要设置其格式的值,可为单个值、元组或字典。
>>> format = "Hello, %s. %s enough for ya?" # 格式字符串中的%s称为转换说明符
>>> values = ("world", "Hot")
>>> format % values
"Hello, world. Hot enough for ya?"
>>> "{}, {} and {}".format("first", "second", "third")
"first, second, third"
>>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")
"to be or not to be"
>>> from math import pi
>>> "{name} is approximately {value:.2f}.".format(value=pi, name="Π")
"Π is approximately 3.14"
>>> "{foo} {} {bar} {}".format(1, 2, foo=3, bar=4)
"3 1 4 2"
>>> "{foo} {} {bar} {}".format(1, 2, foo=3, bar=4)
"3 2 4 1"
>>> from math import e
>>> f"Euler's constant is roughly {e}."
"Euler's constant is roughly 2.718281828459045."
1.2 完整版
# 转换标志:s代表str,r代表repr(字符),a代表ASCII
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="Π"))
Π 'Π' '\u03a0'
>>> print("The number is {num}".format(num=42))
The number is 42
>>> print("The number is {num:f}".format(num=42))
The number is 42.000000
>>> print("The number is {num:b}".format(num=42))
The number is 101010
类型 | 含义 |
b | 将整数表示为二进制数 |
c | 将整数解读为Unicode码点 |
d | 将整数视为十进制数进行处理,这是整数默认使用的说明符 |
e | 使用科学表示法来表示小数(用e来表示指数) |
E | 与e相同,但使用E来表示指数 |
f | 将小数表示为定点数 |
F | 与f相同,但对于特殊值(nan和inf),使用大写表示 |
g | 自动在定点表示法和科学表示法之间做出选择。这是默认用于小数的说明符,但在默认情况下至少有一位小数 |
G | 与g相同,但使用大写来表示指数和特殊值 |
n | 与g相同,但插入随区域而异的数字分隔符 |
o | 将整数表示为八进制数 |
s | 保持字符串的格式不变,这是默认用于字符串的说明符 |
x | 将整数表示为十六进制数并使用小写字母 |
X | 与x相同,但使用大写字母 |
% | 将数表示为百分比值(乘以100,按说明符f设置格式,再在后面加上%) |
设置浮点数的格式时,默认在小数点后有6位小数,并根据需要设定字段的宽度,而不进行任何形式的填充。但我们可以根据自己的需求来设置宽度、精度和千分位分隔符。
>>> "{num:10}".format(num=3) # 指定宽度,数字右对齐
' 3'
>>> "{name:10}".format(name="Bob") # 指定宽度,整数左对齐
'Bob '
>>> from math import pi
>>> "Pi day is {pi:.2f}".format(pi=pi) # 确定精度
'Pi day is 3.14'
>>> "pi:10.2f}".format(pi=pi) #指定宽度和精度
' 3.14'
>>> "pi:010.2f}".format(pi=pi) # 用0填充
'0000003.14'
>>> "One google is {:,}".format(10**100) # 千位分隔符
'One google is 10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000'
>>> print("{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}".format(pi))
'3.14 ' # 左对齐
' 3.14 ' # 居中
' 3.14' # 右对齐
>>> "{:$^15}".format(" WIN BIG ") # 文字居中,左右填充“$”至宽度位15
'$$$ WIN BIG $$$'
>>> print("{0:-.2}\n{0:-.2}".format(pi, -pi))
3.1 # 正数前无任何字符,默认情况
-3.1
>>> print("{0:+.2}\n{0:+.2}".format(pi, -pi))
+3.1 # 正数前有+号
-3.1
>>> print("{0: .2}\n{0: .2}".format(pi, -pi))
3.1 # 正数前有空格
-3.1
# 根据指定的宽度打印格式良好的价格列表
width = int(input("Please enter width:"))
price_width = 10
item_width = width - price_width
header_fmt = "{{:{}}}{{:>{}}}".format(item_width, price_width)
fmt = "{{:{}}}{{:>{}.2f}}".format(item_width, price_width)
print("=" * width)
print(header_fmt.format('Item', 'Price'))
print("-" * width)
print(fmt.format("Apples", 0.4))
print(fmt.format("Pears", 0.5))
print(fmt.format("Cantaloupes", 1.92))
print(fmt.format("Dried Apricots", 8))
print(fmt.format("Prunes", 12))
/'''
运行结果:
Please enter width:25
=========================
Item Price
-------------------------
Apples 0.40
Pears 0.50
Cantaloupes 1.92
Dried Apricots 8.00
Prunes 12.00
'''/
2 字符串方法
2.1 center
通过在两边添加填充字符(默认为空格)让字符串居中。
sentence = "The Middle by Jimmy Eat World"
print(sentence.center(39))
print(sentence.center(39, "*"))
/'''
运行结果:
The Middle by Jimmy Eat World
*****The Middle by Jimmy Eat World*****
'''/
2.2 find
在字符串中查找子串,如果找到就返回子串的第一个字符的索引,否则返回-1。
>>> sentence = "With a moo-moo here, and a moo-moo there"
>>> print(sentence.find("moo"))
7
>>> print(sentence.find("here"))
15
>>> print(sentence.find("here", 18)) # 只指定了起点
36
>>> print(sentence.find("here", 18, 30)) # 指定了起点和终点,含起点不含终点
-1
>>> print(sentence.find("there"))
35
>>> print(sentence.find("With"))
0
>>> print(sentence.find("python"))
-1
2.3 join
合并序列的元素,和spilt的作用恰好相反。
>>> seq = ['1', '2', '3', '4', '5']
>>> ' '.join(seq)
'1 2 3 4 5'
>>> dirs = ('C:', 'usr', 'bin', 'env')
>>> '\\'.join(dirs)
'C:\usr\bin\env'
2.4 lower
返回字符串小写。
>>> sentence = "The Middle by Jimmy Eat World"
>>> sentence.lower()
'the middle by jimmy eat world'
2.5 replace
将指定子串都替换为另一个字符串,并返回替换后的结果。
>>> sentence = "The Middle by Jimmy Eat World"
>>> sentence.replace("World", "Apples")
'The Middle by Jimmy Eat Apples'
2.6 split
拆分字符串,若有参数,按指定字符拆分,否则按空白符拆分(空格、制表符、换行符等)。
>>> sentence = "The Middle by Jimmy Eat World"
>>> sentence.split()
['The', 'Middle', 'by', 'Jimmy', 'Eat', 'World']
>>> sentence.split("l")
['The Midd', 'e by Jimmy Eat Wor', 'd']
2.7 strip
删除字符串开头和结尾的空白,并返回删除后的结果。若有参数则删除指定字符。
>>> sentence = " ** The Middle * by Jimmy ! Eat World !!!***"
>>> sentence.strip()
'** The Middle * by Jimmy ! Eat World !!!***'
>>> sentence.strip(" *!")
'The Middle * by Jimmy ! Eat World'