本文主要介紹了下Python的一些內建字串的方法,包括概覽,字串大小寫轉換,字串格式輸出,字串搜尋定位與替換,字串的聯合與分割,字串條件判斷,字串編碼
字串處理是非常常用的技能,但Python 內建字串方法太多,常常遺忘,為了方便快速參考,特地依據Python 3.5.1 給每個內建方法寫了範例並進行了歸類,便於大家索引。
PS: 可以點選概覽內的綠色標題進入對應分類或透過右側邊欄文章目錄快速索引對應方法。
大小寫轉換
str.capitalize()
將首字母轉換成大寫,需要注意的是如果首字沒有大寫形式,則傳回原始字串。
'adi dog'.capitalize()
# 'Adi dog'
#'abcd 徐'.capitalize()
# 'Abcd 徐'
'徐abcd'.capitalize()
# '徐abcd'
'ß'.capitalize()
# 'SS'
str. lower()
將字串轉換成小寫,其僅對ASCII 編碼的字母有效。
'DOBI'.lower()
# 'dobi'
'ß'.lower() # 'ß' 為德語小寫字母,其有另一種小寫'ss ', lower 方法無法轉換
# 'ß'
'徐ABCD'.lower()
# '徐abcd'
##str.casefold ()
# 'dobi'
# 'ss'
str.swapcase()
#: '徐dOBI A123 SS' 這裡的ß 轉成SS 是一種大寫
但需要注意的是s.swapcase( ).swapcase() == s 不一定為真:
# 'µ'
# 'Μ'
# 'μ'
Out[154]: '0x3bc'
str.title()
# 'Hello World'
# '中文Abc Def 12Gh'
"they're bill's friends from the UK".title()
# "They'Re Bill'S Friends From The Uk"
str.upper()
# '中文ABC DEF 12GH'
需要注意的是 s.upper().isupper() 不一定為 True。
字串格式輸出
將字串依照給定的寬度置中顯示,可以給定特定的字元填充多餘的長度,如果指定的長度小於字串長度,則傳回原始字串。
# '**12345***'
# ' 12345 '
str.ljust(width[, fillchar]); str.rjust(width[, fillchar])
# 'dobi '
# 'dobi~~~~~ ~'
# 'dobi'
# 'dobi'
str.zfill(width)
# '00042'
"-42".zfill(5)
# '-0042'
# '000dd'
# '-000-'
# '0000 '
# '00000'
# '00000'
'dddddddd'.zfill(5)
# ''dddddddd str.expandtabs(tabsize=8)
tab.expandtabs()
# '1 23 456 7890 1112131415 345678123456781234567812345678' 注意空格的計數與上方輸出位置的關係
# '1 23 456 7890 1112131415 161718192021'
# '123412341234123412341234123412342##ad格式化字串的語法比較繁多,官方文件已經有比較詳細的examples,這裡就不寫例子了,想了解的童鞋可以直接戳這裡Format examples.
str.format_map(mapping)
#類似str .format(*args, **kwargs) ,不同的是mapping 是一個字典物件。
People = {'name':'john', 'age':56}
# 'My name is john,i am 56 old'
字串搜尋定位與替換
str.count(sub[, start[, end] ])
text.count('e')
text.count('e', 5, 11)
text.count('e', 5, 10)
str.find(sub[, start[, end]]); str.rfind(sub [, start[, end]])
text = 'outer protective covering'
text.find('er')
# 3
text.find('to ')
text.find('er', 3)
text.find('er', 4)
text.find('er', 4, 21)
text.find('er', 4, 22)
text.rfind('er')
text.rfind('er', 20)
text.rfind('er', 20, 21)
str.index(sub[, start [, end]]); str.rindex(sub[, start[, end]])
與find() rfind() 類似,不同的是如果找不到,就會引發ValueError。
str.replace(old, new[, count])
'dog wow wow jiao'.replace('wow', 'wang')
# 'dog wang wang jiao'
# 'dog wang wow jiao'
'dog wow wow jiao'.replace('wow ', 'wang', 0)
'dog wow wow jiao'.replace('wow', 'wang', 2)
'dog wow wow jiao'.replace('wow', 'wang', 3)
str.lstrip([chars]); str.rstrip([chars]); str.strip([chars])
' dobi'.lstrip()
'db.kun.ac.cn'.lstrip(' dbk')
# '.kun.ac.cn'
' dobi '.rstrip()
# ' dobi'
'db.kun.ac.cn'.rstrip( 'acn')
# 'db.kun.ac.'
' dobi '.strip()
# 'dobi'
'db.kun.ac.cn'.strip ('db.c')
# 'kun.ac.cn'
# 'kun.a'
static str.maketrans(x[, y[, z]]); str.translate(table)
maktrans 是一個靜態方法,用於產生一個對照表,以供translate 使用。
如果maktrans 只有一個參數,則該參數必須是一個字典,字典的key 要么是一個Unicode 編碼(一個整數),要么是一個長度為1 的字串,字典的value 則可以是任意字串、 None或Unicode 編碼。
a = 'dobi'
ord('o')
# 111
# 97
hex( ord('狗'))
b = {'d':'dobi', 111:' is ', 'b':97, 'i':'\u72d7 \u72d7'}
a.translate(table)
##如果maktrans 有兩個參數,則兩個參數形成映射,且兩個字串必須是長度相等;如果有第三個參數,則第三個參數也必須是字串,該字串將自動映射到None:
a = 'dobi is a dog'
table = str.maketrans('dobi', 'alph')
a.translate(table)
# 'alph hs a alg'table = str.maketrans('dobi', 'alph', 'o')a.translate(table)# 'aph hs a ag'
#str.join(iterable)
'-'.join(['2012', '3', '12'])# '2012-3-12'
# TypeError: sequence item 0: expected str instance, int found
'-'.join(['2012', '3', b'12']) #bytes 為非字串
# TypeError: sequence item 2: expected str instance, bytes found
'-'.join(['2012'])
# '2012'
#'-'.join([])
# ''
# TypeError: 序列項目0: 預期的str 實例,找不到NoneType
# ''
# 'dobi,polly'
# 'dog,bird'
str.partition(sep); str.rpartition(sep)
'狗哇哇嬌'.partition('哇')
# ('狗', '哇', '哇嬌')
# ('', '狗', '哇哇嬌')
# ('狗哇哇', 'jiao', '')
# ('狗哇哇嬌', '', '' )
##'狗哇哇嬌'.rpartition('哇')
'狗哇哇嬌'.rpartition('狗')
'狗哇哇嬌'.rpartition('jiao')
'狗哇哇嬌'.rpartition('ww ')
str.split(sep=None, maxsplit=-1); str.rsplit(sep=None, maxsplit=-1)
'1,2,3'.split(','), '1,2,3'.rsplit()
# (['1 ', '2', '3'], ['1,', '2,', '3'])
#'1,2,3'.split(',', maxsplit=1 ), '1,2,3'.rsplit(',', maxsplit=1)
'1 2 3'.split(), '1 2 3'.rsplit()
'1 2 3'.split(maxsplit=1), '1 2 3'.rsplit(maxsplit=1)
' 1 2 3 '.split()
'1,2,,3,'.split(','), '1,2,,3,'.rsplit(',')
''.split()
''.split('a')
# ['']
'bcd'.split('a')
# ['bcd']
'bcd'.split( None)
# ['bcd']
#str.splitlines([keepends])
#字串以行界符分割成清單;當keepends為True ,分割後保留行界符,能被辨識的行界符見官方文件。 ab c', '', 'de fg', 'kl']
# ['ab c \ n', '\n', 'de fg\r', 'kl\r\n']
"".splitlines(), ''.split('\n') #注意兩者的區別
# ([], [''])
"一行\n".splitlines()
# (['一行'], ['兩行', ''])
字串條件判斷
str.endswith(suffix[, start[, end]]); str.startswith(prefix[, start[, end]])text = '外保護層'
text.endswith('ing')
text .endswith(('gin', 'ing'))
#text.endswith('ter', 2, 5)
# True
text.endswith(' ter ', 2, 4)
# False
str.isalnum()
字串和數字的相似組合,即為真,簡而言之:只要c.isalpha(), c.isdecimal(), c.isdigit(), c.isnumeric() 中任意一個為真,則c.isalnum()為真。 ( )
# 真
'徐'.isalnum()
# 真'dobi_123'.isalnum()# False
# False
# False
str.isalpha()
# True
# False
# False
# 真
str.isdecimal(); str.isdigit(); str.isnumeric()
三個方法的差異在於針對 Unicode 通用標識的真值判斷範圍不同:
isdigit: No, Nd,
isnumeric: No 、Nd、Nl
digit 與decimal 的差別在於有些數值字串,是digit 卻非decimal ,具體戳這裡
num = '\u2155'
print(num)
# ⅕
num.isdecimal(), num.isdigit(), num.isnumeric()
# (False, False, True)
num = '\u00B2'
print(num)
# ²
num.isdecimal(), num.isdigit(), num.isnumeric()
# (False, True, True)
num = "1" #unicode
#num .isdecimal(), num.isdigit(), num.isnumeric()
# (Ture, True, True)
num = "'Ⅶ'"
num.isdecimal(), num .isdigit(), num.isnumeric()
# (False, False, True)
num = "十"
num.isdecimal(), num.isdigit(), num.isnumeric ()
# (False, False, 真)
num = b"1" # byte
num.isdigit() # True
num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'
str.isidentifier()
#字串字串是否可為合法的識別碼。
'def'.isidentifier()
'with'.isidentifier()
'false'.isidentifier ()
'dobi_123'.isidentifier()
'dobi 123'.isidentifier()
# '123'.isidentifier()
# False
str.islower()
'徐'.islower()
'ß'.islower() #德語大寫字母
'a徐'.islower()
'ss'.islower()
# False
'Ab'.islower()
判斷字串的所有字元都是可列印字元或字串為空。 Unicode 字元集中 “Other” “Separator” 類別的字元為不可列印的字元(但不包括 ASCII 的空格(0x20))。
# True
Out[24]: False
'dobi 123'.isprintable()
'dobi.123'.isprintable()
## True
str.isspace()
判斷字串中是否至少有一個字符,且所有字元都是空白字符。
Out[29]: True
Out[30]: False
Out[31]: True
'How Python Works'.istitle()
'How Python WORKS'.istitle()
# False
'how python works '.istitle()
'How Python Works'.istitle()
##' '.istitle()
# False
''.istitle()
# False
'A'.istitle()
# True
'a'.istitle()
# False
'甩甩Abc Def 123'.istitle()
# 真
'徐'.isupper()
# False
Out[41]: True'Dobi'.isupper()
# False
'DOBI123'.isupper()
# True
'DOBI 123'.isupper()
# True
'DOBI\t 123'.isupper()
#' DOBI_123'.isupper()
'_123'.isupper()
字串編碼

Tomergelistsinpython,YouCanusethe操作員,estextMethod,ListComprehension,Oritertools

在Python3中,可以通過多種方法連接兩個列表:1)使用 運算符,適用於小列表,但對大列表效率低;2)使用extend方法,適用於大列表,內存效率高,但會修改原列表;3)使用*運算符,適用於合併多個列表,不修改原列表;4)使用itertools.chain,適用於大數據集,內存效率高。

使用join()方法是Python中從列表連接字符串最有效的方法。 1)使用join()方法高效且易讀。 2)循環使用 運算符對大列表效率低。 3)列表推導式與join()結合適用於需要轉換的場景。 4)reduce()方法適用於其他類型歸約,但對字符串連接效率低。完整句子結束。

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python的關鍵特性包括:1.語法簡潔易懂,適合初學者;2.動態類型系統,提高開發速度;3.豐富的標準庫,支持多種任務;4.強大的社區和生態系統,提供廣泛支持;5.解釋性,適合腳本和快速原型開發;6.多範式支持,適用於各種編程風格。

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。