字串類型是python裡面最常見的類型,是不可變類型,支援單引號、雙引號、三引號,三引號是一對連續的單引號或者雙引號,允許一個字串跨多行。
字串串連:前面提到的+操作符可用於字串串連,還可以直接把幾個字串連在一起寫,另外調用join()方法也可以連接字串。
只適用於字串串連的操作符:前面提到了一些序列類型共用的操作符,除此之外,字串還有只屬於自己的操作符,包括格式控制操作符%、字串模板string.Template、原始字串操作符r/R、Unicode字串操作符u/U。
下面列舉一些與字串類型有關的模組。
string:字串操作相關函數和工具,比如Template類。
re:Regex,強大的字串模式比對模組。
struct:字串和二進位之間的切換。
c/StringIO:字串緩衝對象,操作方法類似於file對象。
base64:Base16,32,64資料編解碼。
codecs:解碼器註冊和基類。
crypt:進行單方面加密。
difflib:找出序列間的不同。
hashlib:多種不同安全哈系演算法和資訊摘要演算法的API,python2.5廢除。
hma:HMAC資訊鑒權演算法的python實現。
md5:RSA的MD5資訊摘要鑒權。
rotor:提供多平台的加解密服務。
sha:NIAT的安全哈系演算法SHA。
stringprep:提供用於IP協議的Unicode字串。
textwrap:文本打包和填充。
unicodedata:Unicode資料庫。
Python 3 的源碼的預設編碼方式為 UTF-8
在Python 3,所有的字串都是使用Unicode編碼的字元序列。
utf-8 是一種將字元編碼成位元組序列的方式。位元組即位元組,並非字元。字元在電腦內只是一種抽象。字串則是一種抽象的序列。在這裡我們只討論字串,不討論位元組。
在Python 中,字串可以用單引號括起來,也可以用雙引號,甚至是三引號。
但如果字串中含有單引號,你應該用雙引號來括,或者用轉義符加單引號括起來。含有雙引號的同理。
三引號的字串可以換行!
>>> 'Let's go!' SyntaxError: invalid syntax >>> "Let's go!" "Let's go!" >>> 'Let\'s go!' "Let's go!" >>> '''''begin and next end''' 'begin\nand\nnext\nend'
字串是不可修改的,這點很重要!你可以把它想象為字元組成的元組。
>>> s = "HelloWorld" >>> s[0] = 'h' Traceback (most recent call last): File "", line 1, in s[0] = 'h' TypeError: 'str' object does not support item assignment
如果你想修改它,可以先轉換成列表,修改完成後再轉為字串。
>>> s 'HelloWorld' >>> L = list(s) >>> L ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd'] >>> L[0] = 'h' >>> ''.join(L) #這是什麼?別著急,下面我們會談到 'helloWorld'
字串可以進行直接拼接,但如果是兩個變數代表的字串,你還是用 + 號吧
>>> s = "Hello""World" >>> s 'HelloWorld' >>> s1 = "Hello" >>> s2 = "World" >>> s1s2 Traceback (most recent call last): File "", line 1, in s1s2 NameError: name 's1s2' is not defined >>> s1+s2 'HelloWorld'
字串操作和方法:
len(s) 返回字串長度
x in s 查詢 x 是否在 s 中
>>> s = "HelloWorld" >>> len(s) 10 >>> "ll" in s True
s.find( x ) 在字串 s 中找子串 x ,找到則返回最左端的索引,找不到則返回-1
>>> s 'HelloWorld' >>> s.find("l") 2 >>> s.find('w') -1
s.splitlines() 將多行字串分割成多個單行字串組成的列表,分行符號被吸收
>>> s = '''''begin ...then.. ...next.. end...''' >>> s.splitlines() ['begin', '...then..', '...next..', 'end...']
s.split( x ) 以 x 作為分隔字元將 s 分割成一個字串列表,如果不提供x,則程式會自動將所有空格和換行作為分隔字元分割
>>> s = "here#there" >>> s.split('#') # #作為分隔字元 ['here', 'there'] >>> s = '''''begin .then.. and .next. end''' >>> s.split() #預設情況將所有換行和空格都分割 ['begin', '.then..', 'and', '.next.', 'end']
s.lower() 返回s 的小寫形式的字串
s.upper() 返回 s 的大寫形式的字串
>>> s = 'HelloWorld' >>> s.lower() 'helloworld' >>> s.upper() 'HELLOWORLD'
s.join( seq ) split 的逆方法,將序列 seq 用 s 串連起來,必須是字串序列
>>> L = ['1','33','42'] >>> '+'.join(L) #用+來串連 '1+33+42' >>> L = list(s) #拆開s >>> L ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd'] >>> ''.join(L) #粘合了。。。 'HelloWorld'
s.replace( x, y) 將 s 中所有匹配 x 的項用 y 代替,如果找不到,那就直接返回 s 咯
>>> s 'HelloWorld' >>> s.replace("World","Cheng") 'HelloCheng' >>> s.replace("world","Cheng") #知道為什麼吧... 'HelloWorld'
s.strip( x ) 如果不提供 x,那麼返回去除了首尾兩側空格的字串,如果提供了字串 x,那麼將去除s首尾所有在 x 中的字元並返回
>>> s = " Hi,I'm Alice! " >>> s.strip() "Hi,I'm Alice!" >>> s.strip("! ") #這是兩個字元哦 "Hi,I'm Alice" #少了一個驚嘆號哦!
再次注意:以上方法都沒有改變原字串,字串是不可改變的!
以下簡單看看:
s.starstwith( x ) 測試 s 是否以 x 開頭
s.endswith( x ) 測試 s 是否以 x 結尾
s.isalnum() 測試 s 是否全是字母和數字,並至少有一個字元
s.isalpha() 測試 s 是否全是字母,並至少有一個字元
s.isdigit() 測試 s 是否全是數字,並至少有一個字元
s.isspace() 測試 s 是否全是空白字元,並至少有一個字元
s.islower() 測試 s 中的字母是否全是小寫
s.isupper() 測試 s 中的字母是否便是大寫
s.istitle() 測試 s 是否是首字母大寫的
讓我們重點關注一個強大的格式化方法 format ,看下面代碼
>>> name = 'Jonh' >>> call = '13560300xxx' >>> "{0}'s telephone number is {1}".format(name,call) # (1) "Jonh's telephone number is 13560300xxx" >>> addr = "A103" >>> "{0}'s telephone number is {1} and his address is {2}".format(name,call,addr) #(2) "Jonh's telephone number is 13560300xxx and his address is A103"
(1)句中,字串中 {0} 被 format 的第一個參數代替,{1} 被第二個參數代替。兩個參數不夠?事實上,你可以給予它任意多個參數,然後用相同個數的替換欄位進行替換。什麼是替換欄位?{0},{1}就叫做替換欄位。我們在第(2)句中使用了3個替換欄位,{0}對應name, {1}對應call,{2}對應addr。再多的參數也類似於剛才的做法。
那麼,僅僅是這樣?當然不是!讓我們繼續看
>>> L = [2,3,5,7] >>> print("x is {0[0]}, y is {0[2]}".format(L)) x is 2, y is 5
{0[0]} 表示L[0],{0[2]} 表示L[2],它們叫做複合欄位名,你可以:
(1)使用列表作為參數,並且通過下標索引來訪問其元素(跟上一例類似)
(2)使用字典作為參數,並且通過鍵來訪問其值
>>> d {'b': 2, 'a': 1} >>> print("x is {0[a]}, y is {0[b]}".format(d)) x is 1, y is 2 >>> d = {2:3.5,7:4.5} >>> print("x is {0[2]}, y is {0[7]}".format(d)) x is 3.5, y is 4.5
d 為字典,a 、b為鍵,{0[a]} 對應到了值2(注意:是a,b,不是'a', 'b')
(3)使用模組作為參數,並且通過名字來訪問其變數及函數
>>> print("{0.random}".format(random))
(4)使用類的執行個體作為參數,並且通過名字來訪問其方法和屬性
>>> class A: pass >>> x = A() >>> print("The class is {0.__class__}".format(x)) The class is
(5)以上方法的任意組合
替換欄位除了整數,你還可以使用參數名字
>>> print("{name}'s telephone number is {call}".format(name = "Jonh",call = 69993)) Jonh's telephone number is 69993
在替換域中,你還可以使用格式說明符。冒號 : 標示格式說明符的開始。
>>> pi = 3.141592653 >>> print("The pi is {0:10.3f}".format(pi)) # 0:10.3f 表示輸出寬度為10,保留三位小數,浮點數 The pi is 3.142