Python--字符串使用方法總結

python字符串有很多種操作方法,這裏做出總結方便平時查找使用。

sort

描述:sort() 函數用於對原列表進行排序,如果指定參數,則使用比較函數指定的比較函數。

語法:list.sort(cmp=None, key=None, reverse=False)

參數:

  • cmp -- 可選參數, 如果指定了該參數會使用該參數的方法進行排序。
  • key -- 主要是用來進行比較的元素,只有一個參數,具體的函數的參數就是取自於可迭代對象中,指定可迭代對象中的一個元素來進行排序。
  • reverse -- 排序規則,reverse = True 降序, reverse = False 升序(默認)。

示例:

>>> list=[2,3,5,4,9,6]
>>> list.sort()
>>> list
[2, 3, 4, 5, 6, 9]
>>> list.sort()
>>> list.sort(reverse=False)
>>> list
[2, 3, 4, 5, 6, 9]
>>> list.sort(reverse=True)
>>> list
[9, 6, 5, 4, 3, 2]
>>> 

find

find方法可以在一個較長的字符串中查找子字符串。它返回子串所在位置的最左端索引。如果沒有找到則返回-1。

>>> a = 'test'
>>> a.find('s')
2
>>> 

find方法其實和列表取步長的方法聯用來截取某段需要的字符串。

>>> a  = 'hello world'
>>> iwantstring = a[a.find('w'):a.find('r')]
>>> iwantstring
'wo'
>>>

join

join方法是非常重要的字符串方法,它是split方法的逆方法,用來在隊列中添加元素。注意:需要添加的隊列元素都必須是字符串。

>>> test = ['a','b','c','d']
>>> out = '+'.join(test)
>>> out
'a+b+c+d'

replace

replace方法返回某個字符串的所有匹配項均被替換之後得到的字符串。

>>> a  = 'hello world'
>>> b = a.replace('l','t')
>>> b
'hetto wortd'
>>> 

split

這是個非常重要的字符串方法,它是join的逆方法,用來將字符串按指定字符串元素進行分割並返回列表。注意:如果不提供任何分隔符,程序會把所有空格作爲分隔符(空格、製表、換行等)

>>> a  = 'hello world'
>>> b = a.split('l')
>>> b
['he', '', 'o wor', 'd']
>>> 

strip

strip方法返回去除兩側(不包含內部)空格的字符串

>>> a = '   hello world    '
>>> b = a.strip()
>>> b
'hello world'
>>> 

translate

translate方法和replace方法一樣,可以替換字符串中的某些部分,但是和前者不同的是,translate方法只處理單個字符。它的優勢在於可以同時進行多個替換,有些時候比replace效率高得多。
在使用translate轉換前,需要先完成一張轉換表。轉換表中是以某字符替換某字符的對應關係。因爲這個表(事實上是字符串)有多達256個項目,我們還是不要自己寫了,用string模塊裏面的maketrans函數就行了。

maketrans函數接收兩個參數:兩個等長的字符串,表示第一個字符串中的每個字符都用第二個字符串中相同位置的字符替換。

>>> from string import maketrans
>>> table = maketrans('ho', 'at')

創建這個表後,可以將它用作translate方法的參數,進行字符串的轉換:

>>> a  = 'hello world'
>>> b = a.translate(table)
>>> b
'aellt wtrld'

translate的第二個參數是可選的,這個參數是用來指定需要刪除的字符。

>>> b = a.translate(table, ' ')
>>> b
'aelltwtrld'
>>> 

= 生成字符串變量

>>> test = 'hello world'
>>> test
'hello world'
>>> 

len 字符串長度獲取

>>> a  = 'hello world'
>>> b = len(a)
>>> b
11
>>> 

+ 連接字符串

>>> a = 'hello'
>>> b = ' '
>>> c = 'world'
>>> d = a+b+c
>>> d
'hello world'
>>> 

cmp 比較字符串

>>> a = 'hello'
>>> b = 'world'
>>> c = cmp(a,b)
>>> c
-1
>>> 

[] 截取字符串

注意:一定要搞清楚下標是從0開始的,列表右邊的元素是不被包含的

>>>a = '0123456789'
>>>b = a[0:3] # 截取第一位到第三位的字符
>>>b
'012'

>>>b = a[:] # 截取字符串的全部字符
>>>b
'0123456789' 

>>>b = a[6:] # 截取第七個字符到結尾
>>>b
'6789' 

>>>b = a[:-3] # 截取從頭開始到倒數第三個字符之前
>>>b
'0123456'

>>>b = a[2] # 截取第三個字符
>>>b
'2' 

>>>b = a[-1] # 截取倒數第一個字符
>>>b
'9' 

>>>b = a[::-1] # 創造一個與原字符串順序相反的字符串
>>>b
'9876543210' 

>>>b = a[-3:-1] # 截取倒數第三位與倒數第一位之前的字符
>>>b
'78' 

>>>b = a[-3:] # 截取倒數第三位到結尾
>>>b
'789'

字符串中的搜索和替換

S.find(substr, [start, [end]])   
#返回S中出現substr的第一個字母的標號,如果S中沒有substr則返回-1。start和end作用就相當於在S[start:end]中搜索
S.index(substr, [start, [end]])   
#與find()相同,只是在S中沒有substr時,會返回一個運行時錯誤
S.rfind(substr, [start, [end]])   
#返回S中最後出現的substr的第一個字母的標號,如果S中沒有substr則返回-1,也就是說從右邊算起的第一次出現的substr的首字母標號
S.rindex(substr, [start, [end]])
S.count(substr, [start, [end]])    
#計算substr在S中出現的次數
S.replace(oldstr, newstr, [count])    
#把S中的oldstr替換爲newstr,count爲替換次數。這是替換的通用形式,還有一些函數進行特殊字符的替換
S.strip([chars]) 
#把S中前後chars中有的字符全部去掉,可以理解爲把S前後chars替換爲None
S.lstrip([chars])
S.rstrip([chars])
S.expandtabs([tabsize])   
#把S中的tab字符替換沒空格,每個tab替換爲tabsize個空格,默認是8個

字符串的分割和組合:

S.split([sep, [maxsplit]]) 
# 以sep爲分隔符,把S分成一個list。maxsplit表示分割的次數。默認的分割符爲空白字符
S.rsplit([sep, [maxsplit]])
S.splitlines([keepends]) 
# 把S按照行分割符分爲一個list,keepends是一個bool值,如果爲真每行後而會保留行分割符。
S.join(seq) 
# 把seq代表的序列──字符串序列,用S連接起來

字符串的mapping,這一功能包含兩個函數:
String.maketrans(from, to)

# 返回一個256個字符組成的翻譯表,其中from中的字符被一一對應地轉換成to,所以from和to必須是等長的。
S.translate(table[,deletechars]) 
#  使用上面的函數產後的翻譯表,把S進行翻譯,並把deletechars中有的字符刪掉。需要注意的是,如果S爲unicode字符串,那麼就不支持 deletechars參數,可以使用把某個字符翻譯爲None的方式實現相同的功能。此外還可以使用codecs模塊的功能來創建更加功能強大的翻譯 表。

字符串中字符大小寫的變換:

S.lower()   #小寫
S.upper()   #大寫
S.swapcase()   #大小寫互換
S.capitalize()   #首字母大寫
String.capwords(S)  #這是模塊中的方法。它把S用split()函數分開,然後用
capitalize()把首字母變成大寫,最後用join()合併到一起
S.title()    #只有首字母大寫,其餘爲小寫,模塊中沒有這個方法

字符串去空格及去指定字符

去兩邊空格:str.strip()
去左空格:str.lstrip()
去右空格:str.rstrip()
去兩邊字符串:str.strip('d'),相應的也有lstrip,rstrip
str=' python String function '
print '%s strip=%s' % (str,str.strip())
str='python String function'
print '%s strip=%s' % (str,str.strip('d'))

字符串編碼和解碼的函數:

S.encode([encoding,[errors]]) 
# 其中encoding可以有多種值,比如gb2312 gbk gb18030 bz2 zlib big5 bzse64等都支持。errors默認值爲strict,意思是UnicodeError。可能的值還有'ignore', 'replace', 'xmlcharrefre
S.encode([encoding,[errors]]) 
# 其中encoding可以有多種值,比如gb2312 gbk gb18030 bz2 zlib big5 bzse64等都支持。errors默認值爲"strict",意思是UnicodeError。可能的值還有'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 和所有的通過codecs.register_error註冊的值。這一部分內容涉及codecs模塊,不是特明白
S.decode([encoding,[errors]])

字符串的測試函數,這一類函數在string模塊中沒有,這些函數返回的都是bool值:

S.startwith(prefix[,start[,end]]) #是否以prefix開頭
S.endwith(suffix[,start[,end]])  #以suffix結尾
S.isalnum()  #是否全是字母和數字,並至少有一個字符
S.isalpha()  #是否全是字母,並至少有一個字符
S.isdigit()  #是否全是數字,並至少有一個字符
S.isspace() #是否全是空白字符,並至少有一個字符
S.islower() #S中的字母是否全是小寫
S.isupper() #S中的字母是否便是大寫
S.istitle() #S是否是首字母大寫的

字符串類型轉換函數,這幾個函數只在string模塊中有:

string.atoi(s[,base])  
# base默認爲10,如果爲0,那麼s就可以是012或0x23這種形式的字符串,如果是16那麼s就只能是0x23或0X12這種形式的字符串
string.atol(s[,base])  
# 轉成long
string.atof(s[,base])  
# 轉成float

python字符串與數字的轉化

數字變爲字符串 str()
字符串變爲數字 string.atoi(s,[,base]) //base爲進制基數
浮點數轉換 string.atof(s)

字符串在輸出時的對齊:

S.ljust(width,[fillchar])   #輸出width個字符,S左對齊,不足部分用fillchar填充,默認的爲空格。
S.rjust(width,[fillchar])    #右對齊
S.center(width, [fillchar])    #中間對齊
S.zfill(width)   #把S變成width長,並在右對齊,不足部分用0補足

字符串中的單引號,雙引號用 \ 來轉義。

把字符串轉換成數字

int('1234')
string模塊裏有
import string
>>> a="12345"
>>> import string
>>> string.atoi(a)
12345
>>> b="123.678"
>>> string.atof(b)
123.678

textwrap 使用 textwrap 模塊來格式化字符串的輸出

s = "Look into my eyes, look into my eyes, the eyes, the eyes, \
the eyes, not around the eyes, don't look around the eyes, \
look into my eyes, you're under."

>>> import textwrap
>>> print(textwrap.fill(s, 70))
Look into my eyes, look into my eyes, the eyes, the eyes, the eyes,
not around the eyes, don't look around the eyes, look into my eyes,
you're under.

>>> print(textwrap.fill(s, 40))
Look into my eyes, look into my eyes,
the eyes, the eyes, the eyes, not around
the eyes, don't look around the eyes,
look into my eyes, you're under.

>>> print(textwrap.fill(s, 40, initial_indent='    '))
    Look into my eyes, look into my
eyes, the eyes, the eyes, the eyes, not
around the eyes, don't look around the
eyes, look into my eyes, you're under.

>>> print(textwrap.fill(s, 40, subsequent_indent='    '))
Look into my eyes, look into my eyes,
    the eyes, the eyes, the eyes, not
    around the eyes, don't look around
    the eyes, look into my eyes, you're
    under.

textwrap 模塊對於字符串打印是非常有用的,特別是當你希望輸出自動匹配終端大小的時候。 你可以使用 os.get_terminal_size() 方法來獲取終端的大小尺寸

>>> import os
>>> os.get_terminal_size().columns
80
>>>

fill() 方法接受一些其他可選參數來控制tab,語句結尾等。 參閱 textwrap.TextWrapper文檔 獲取更多內容。

在字符串中處理html和xml

你想將HTML或者XML實體如 &entity; 或 &#code; 替換爲對應的文本。 再者,你需要轉換文本中特定的字符(比如<, >, 或 &)。

解決方案:如果你想替換文本字符串中的 ‘<’ 或者 ‘>’ ,使用 html.escape() 函數可以很容易的完成。比如:

>>> s = 'Elements are written as "<tag>text</tag>".'
>>> import html
>>> print(s)
Elements are written as "<tag>text</tag>".
>>> print(html.escape(s))
Elements are written as &quot;&lt;tag&gt;text&lt;/tag&gt;&quot;.

>>> # Disable escaping of quotes
>>> print(html.escape(s, quote=False))
Elements are written as "&lt;tag&gt;text&lt;/tag&gt;".
>>>

如果你正在處理的是ASCII文本,並且想將非ASCII文本對應的編碼實體嵌入進去, 可以給某些I/O函數傳遞參數errors=’xmlcharrefreplace’ 來達到這個目。比如:

>>> s = 'Spicy Jalapeño'
>>> s.encode('ascii', errors='xmlcharrefreplace')
b'Spicy Jalape&#241;o'
>>>

爲了替換文本中的編碼實體,你需要使用另外一種方法。 如果你正在處理HTML或者XML文本,試着先使用一個合適的HTML或者XML解析器。 通常情況下,這些工具會自動替換這些編碼值,你無需擔心。

有時候,如果你接收到了一些含有編碼值的原始文本,需要手動去做替換, 通常你只需要使用HTML或者XML解析器的一些相關工具函數/方法即可。比如:

>>> s = 'Spicy &quot;Jalape&#241;o&quot.'
>>> from html.parser import HTMLParser
>>> p = HTMLParser()
>>> p.unescape(s)
'Spicy "Jalapeño".'
>>>
>>> t = 'The prompt is &gt;&gt;&gt;'
>>> from xml.sax.saxutils import unescape
>>> unescape(t)
'The prompt is >>>'
>>>

討論

在生成HTML或者XML文本的時候,如果正確的轉換特殊標記字符是一個很容易被忽視的細節。 特別是當你使用 print() 函數或者其他字符串格式化來產生輸出的時候。 使用像 html.escape() 的工具函數可以很容易的解決這類問題。

如果你想以其他方式處理文本,還有一些其他的工具函數比如 xml.sax.saxutils.unescapge() 可以幫助你。 然而,你應該先調研清楚怎樣使用一個合適的解析器。 比如,如果你在處理HTML或XML文本, 使用某個解析模塊比如 html.parse 或 xml.etree.ElementTree 已經幫你自動處理了相關的替換細節。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章