Python 字串操作
在 Python 中,有一個標準庫,稱為 **string**。在 string 模組中,提供了各種與字串相關的常量、方法和類。
要使用這些模組,我們需要在程式碼中匯入 **string 模組**。
import string
一些字串常量及其對應值如下:
序號 | 字串常量及值 |
---|---|
1 | string.ascii_lowercase ‘abcdefghijklmnopqrstuvwxyz’ |
2 | string.ascii_uppercase ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’ |
3 | string.ascii_letters ascii_lowercase 和 ascii_uppercase 的連線 ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’ |
4 | string.digits ‘0123456789’ |
5 | string.hexdigits ‘0123456789abcdefABCDEF’ |
6 | string.octdigits ‘01234567’ |
7 | string.punctuation ‘!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~’ |
8 | string.printable 所有可列印的 ASCII 字元。它是 ascii_letters、punctuation、digits 和 whitespace 的集合。‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ \t\n\r\x0b\x0c’ |
9 | string.whitespace ‘\t\n\r\x0b\x0c’ |
示例程式碼
import string print(string.hexdigits) print(string.ascii_uppercase) print(string.printable)
輸出
0123456789abcdefABCDEF ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
字串格式化
Python 中內建的字串類透過 `format()` 方法支援不同的複雜變數替換和值格式化。
要格式化字串,基本語法如下:
‘{} {}’.format(a, b)
變數 a 和 b 的值將被放置在用 ‘{}’ 包裹的位置。我們也可以在括號內提供位置引數。或者在括號內寫入一些變數名也是有效的。
使用此格式化選項,我們還可以設定文字的填充。要在文字中新增填充,語法如下:
‘{: (character) > (width)}’.format(‘string’)
使用指定的 **字元**、**寬度** 值,使用 > 符號向右填充“字串”。我們可以使用 < 向左填充,使用 ^ 設定到中間。
format() 方法還可以使用給定的長度截斷字串。語法如下:
‘{:.length}’.format(‘string’)
字串將被截斷到給定的長度。
示例程式碼
print('The Name is {} and Roll {}'.format('Jhon', 40)) print('The values are {2}, {1}, {3}, {0}'.format(50, 70, 30, 15)) #Using positional parameter print('Value 1: {val1}, value 2: {val2}'.format(val2 = 20, val1=10)) #using variable name #Padding the strings print('{: >{width}}'.format('Hello', width=20)) print('{:_^{width}}'.format('Hello', width=20)) #Place at the center. and pad with '_' character #Truncate the string using given length print('{:.5}'.format('Python Programming')) #Take only first 5 characters
輸出
The Name is Jhon and Roll 40 The values are 30, 70, 15, 50 Value 1: 10, value 2: 20 Hello _______Hello________ Pytho
字串模板
字串模板用於以更簡單的方法替換字串。模板支援使用 $ 字元進行替換。當找到 **$識別符號** 時,它將用識別符號的新值替換它。
要在字串中使用模板,基本語法如下:
myStr = string.Template(“$a will be replaced”) myStr.substitute(a = ‘XYZ’)
字串中的 a 值將被字串中的 'XYZ' 替換。我們可以使用字典來執行此類操作。
示例程式碼
my_template = string.Template("The value of A is $X and Value of B is $Y") my_str = my_template.substitute(X = 'Python', Y='Programming') print(my_str) my_dict = {'key1' : 144, 'key2' : 169} my_template2 = string.Template("The first one $key1 and second one $key2") my_str2 = my_template2.substitute(my_dict) print(my_str2)
輸出
The value of A is Python and Value of B is Programming The first one 144 and second one 169
廣告