較全面的Python字符串操作指南
字符串的定義
日常編碼中,大家會發現,太多時候我們需要對數據進行處理,而這數據不管是數組、列表、字典,最終都逃不開字符串的處理。
所以今天要來跟大家發散的聊聊字符串!
估計很多人看到是將字符串肯定覺得索然無味(老子都會),可大佬們不妨再往下看看?
python定義字符、字符串沒有java那樣的嚴格,不管是單引號、雙引號、甚至是三個單引號和雙引號都可以用來定義字符(串),只要成對出現即可。比如:
- # 單個字符
- a='a'
- # 使用單引號定義字符串
- name='Uranus'
- # 使用雙引號定義字符串
- code = "Hello World ..."
- # 既然說到了string,怎么能不點開源碼看看呢?
- class str(object):
- """
- str(object='') -> str
- str(bytes_or_buffer[, encoding[, errors]]) -> str
- Create a new string object from the given object. If encoding or
- errors is specified, then the object must expose a data buffer
- that will be decoded using the given encoding and error handler.
- Otherwise, returns the result of object.__str__() (if defined)
- or repr(object).
- encoding defaults to sys.getdefaultencoding().
- errors defaults to 'strict'.
- """
雖然這些不是主要說的,但還是簡單提下,三個單引號或者雙引號,主要是用來作為文檔注釋的,請不要拿來定義字符串(雖然這樣并不會出現語法錯誤)。
今天主要說下關于打段的字符串應該如何定義,PEP8有規定,一行代碼的長度請勿超過120個字符。那么如果遇到這種情況,該怎么辦?
- # 不推薦的使用方式:
- line = """
- Create a new string object from the given object.
- If encoding or errors is specified,
- then the object must expose a data buffer that will be
- decoded using the given encoding and error handler.
- """
- # 或者這樣
- line = "Create a new string object from the given object. " \
- "If encoding or errors is specified," \
- "then the object must expose a data buffer that will be" \
- " decoded using the given encoding and error handler."
- # 更好的實現方式:
- line = ("Create a new string object from the given object."
- "If encoding or errors is specified,"
- "then the object must expose a data buffer that will be "
- "decoded using the given encoding and error handler."
- )
字符串中.is()的用法
.is*(), 既然是is,那么它返回的結果只有兩種,True or False
先來對比一下數字:
- isdigit()
- True: Unicode數字,byte數字(單字節),全角數字(雙字節),羅馬數字
- False: 漢字數字
- Error: 無
- isdecimal()
- True: Unicode數字,全角數字(雙字節)
- False: 羅馬數字,漢字數字
- Error: byte數字(單字節)
- isnumeric()
- True: Unicode數字,全角數字(雙字節),羅馬數字,漢字數字
- False: 無
- Error: byte數字(單字節)
總結幾個偏門知識點:
- a='①②③④⑤'
- isdigit()、isnumeric() 為True isdecimal()為False
- b='一壹'
- isnumeric()會認為是True的哦!
再來看一個等式:
- isalnum() = isdigit() + isalpha() + isspace()
- isdigit()表示字符串內全部為數字
- isalpha()表示字符串內全部為字符
- isspace()表示字符串有一個或多個空格組成
- isalnum()表示字符串內全部為數字和字符
- a='12345'
- b='①②③④⑤'
- c='abc123'
- print(a.isdigit()) # True
- print(b.isalpha()) # True
- print(c.isalnum()) # True
針對字符串大小寫的方法:
- .isupper() 字符串全部由大寫組成
- .islower() 字符串全部由小寫組成
- .istitle() 字符串形式為駝峰命名,eg:"Hello World"
以上這些用法去掉is,則變為了對應的字符串轉發方法。學一套會兩套,買一送一….
最后說一個不帶.的is* --- isinstance(obj,type)。
- 判斷一個object是什么類型…
- type可選類型為:int,float,bool,complex,str,bytes,unicode,list,dict,set,tuple
- 并且type可以為一個原組:isinstance(obj, (str, int))
判斷字符串中的內容
.*with() starts ends 不僅支持開頭結尾的匹配,還支持start和end兩個參數來動態定義字符串的index位置。
- long_string = "To live is to learn,to learn is to better live"
- long_string.startswith('To')
- long_string.startswith('li', 3, 5)
- long_string.endswith('live')
- long_string.endswith('live', 0, 7)
同樣支持start、end來判斷字符串的還有 .find()、.rfind()和 .index()、.rindex()
這兩類字符串尋址方法均支持從左到右、從右至左兩種尋址方式,不同的是:
find在未找到時,返回-1,而index在未找到時,會拋出ValueError的異常…
- long_string.index('live') # 3
- long_string.rindex('live') # 42
字符串的內容變更
狹義來說使用,字符串的替換使用.replace()即可,那為什么還要單獨說呢?因為它有一個可選參數count。
- long_string = "To live is to learn,to learn is to better live"
- long_string.count('live') # 2
- long_string.replace('live','Live',1)
- output:
- 'To Live is to learn,to learn is to better live'
- # 可以看到,第二個live并未進行替換
剛才說了狹義,那么廣義呢?
1.(l/r)strip()
將字符串左、右、兩端的特定字符過濾掉,默認為空格…
strip()要注意的地方是,strip('TolLive') 中的字符并非完整匹配,而是針對每一個字符進行匹配,說起來混,直接上例子:
- long_string = "To live is to learn,to learn is to better live"
- long_string.strip('TolLive')
- 's to learn,to learn is to better'
2.字符串切片
字符串的切片分為long_string[start:end;step] start、end區間為左閉右開…這個網上說的太多了,再拉出來詳細講就要挨打了…
(l/r)just(width,[fillchar])、center(width, [fillchar])、zfill(width)
這些均為填充固定長度的字符,默認使用空格(zfill為左補0,z是zero的意思…),看意思就明白了,不用多講了….
字符串格式化輸出
本來fill和center等可以放在這里,但是他們使用頻率和重量級不夠格,就丟在上面了。
Python格式化輸出分為兩類,那是在pyton2的時代,即 % 和 format。這兩種網上的資料太多了,說的太多顯得沒逼格…
但,還是要簡單說說其中特殊的地方。
1.% 格式化輸出:
- 如何在%的格式輸出中,輸出用來看做標記為的%符號呢?使用兩個百分號(%%)
- %(-)(width) width為設置長度,默認左填充空格,添加-號為右填充
- .width代表字符串截斷,保留多少長度的字符串
- type %s字符串 %d十進制整數 %f小數 …
- 多個參數是,后面的參數需要使用括號包裹起來
- '姓名:%-5s 年齡:%4d 愛好: %.8s' % ('王大錘',30,'python、Java')
- output:
- '姓名:王大錘 年齡: 30 愛好:python、J'
2.format格式輸出:
format在python3開始官方就表示為替換%的輸出方式,之所以還保留著%,主要是為了兼容性考慮…
- 對比%,format使用花括號{}表示變量
- < > ^ 代表了format的對齊方式
- '{:-^40s}'.format('華麗的分割線')
- output:
- '-----------------華麗的分割線-----------------'
3.f-string
Python3.6的版本更新時,新增了f-string,英文好的可以去看官方解釋PEP 498 -- Literal String Interpolation 。
f-string是字符串引號前以f/F開頭,并使用{}標注替換位置的使用形式。
之所以官方推出f-string,主要是因為它的更高的性能、更強的功能。例子走起:
- name = 'Uranus'
- f'Hello,{name}'
- f'Hello,{name.lower()}'
- f'Hello,{name:^10s}'
- f'Hello,{(lambda x: x*2) (name)}'
- output:
- 'Hello,Uranus'
- 'Hello,uranus'
- 'Hello, Uranus '
- 'Hello,UranusUranus'
怎么說,是高端了一些,但我這人有點念舊啊…