字符串是序列的一種,因此標準序列操作都適用於字符串,但字符串是不可變的。因此任何元素賦值和切片賦值都是非法的。
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'