Python的字符串

Python有內置的字符串類型, 內置的字符串是序列(Sequence), 是不可變的序列,  因此不可變序列通用的方法對其都適用.html

 

 

對Python2, 內置的字符串類型有strunicodepython

Python2git

'abc' 是str, u'中國123'  是unicode函數

# Python2.7
>>> type('abc')
<type 'str'>
>>> type(u'中國123')
<type 'unicode'>

 

若是咱們使用Python2, 應該都儘可能使用unicode,就算是純英文的. 編碼

 

Python3spa

但在Python3中, 沒有預約義unicode類型了,內置字符串就是str, 可是str中的字符都是unicode編碼的 code

#Python3.3
>>> type(u'中國')
<class 'str'>
>>> type('abc')
<class 'str'>
>>> type(str)
<class 'type'>
>>> type(unicode)
NameError: name 'unicode' is not defined

 

 

 

 

下面討論一些Python內置字符串經常使用的方法, Python2中這些方法對str和unicode基本都是同樣的, 沒有討論到的去文檔查閱就行,基本上須要的功能都有方法實現.htm

 

字符串分隔, split對象

str.split()接受分隔字符串, 返回分隔後的一個listblog

>>> s = 'wangyu@lvye.cn'
>>> s.split('@')
['wangyu', 'lvye.cn']

 

若是同一個分隔符連續多個存在,則在返回結果中會有空字符串

>>> s = 'wangyu@@@@lvye.cn'
>>> s.split('@')
['wangyu', '', '', '', 'lvye.cn']

4個連續的@產生了3個空串

 

當分隔字符串是多字符的,必須是全匹配

>>> s = 'abc<>cba'
>>> s.split('<>')
['abc', 'cba']

 

 一個反面例子

>>> s = 'abc<>cba%$acb'
>>> s.split('<>$')
['abc<>cba%$acb']

 

str.split()也能夠不接受參數,這時候是使用空格作分隔,且不產生空串,若是開頭和結尾有空格,也會被忽略掉

>>> s = ' we are the   champion'
>>> s.split()
['we', 'are', 'the', 'champion']

 

 

子串替換

  str.replace(old, new [, count])

replace把old替換成new,而且能夠指定替換個數, 並且函數返回一個copy,不會影響原來的str對象.

>>> s = 'he is nate, nate is his name'
>>> s.replace('nate', 'sky')
'he is sky, sky is his name'
>>> s
'he is nate, nate is his name'

 

 

 

 

子串查找

字串查找用find()或index(),  其中index()是序列通用的方法

不一樣的是若沒找到find()返回-1, index()拋出異常ValueError, 找到返回字串索引.

find()和index()的語法相同

 

str.find(substr [, start [, end]])

 

普通使用

>>> s='we are are the champion'
>>> s.find('ar')
3

加上範圍

>>> s='we are are the champion'
>>> s.find('ar', 4)
7

 

注意,若是隻是想知道一個字符串是否包含一個子串,使用 in 

>>> s = 'we are the champion'
>>> 'are' in s
True

 

 

字符串的strip

一樣的strip會copy一份原來的字串進行處理.

不加任何參數,去除左右的空格

>>> s = '    www.lvye.cn  '
>>> s.strip()
'www.lvye.cn'

 

帶上參數

>>> s.strip('wcn. ')
'lvye'

注意帶上參數時,空格要顯示指定.

strip還能夠去除兩端的換行符

 

 

字符串其它的方法

  •  isalpha()  是否都是字母
  •  isdigit()    是否都是數字
  •  upper()    都轉化爲大寫

 

Python str的方法,Python文檔中很全.

------------------------- 

 參考:

http://docs.python.org/3/library/stdtypes.html#str   Python文檔

相關文章
相關標籤/搜索