灰色框里面的方法就是所有字符串處理的方法
字符串能使用的所有方法.png
1、strip: 去除首尾的空白符
s = '\n hello word \n\t\r'
# 左右都去除
all = s.strip()
all = 'hello word'
# 左去除
left = s.lstrip()
left = 'hello word \n\t\r'
# 右去除
right = s.rstrip()
right = '\n hello word'
python對字符串s的處理是一個set,而不是一個固定順序的字符串。也就是說,是把s拆開成由單個字母組成的set來看的,如果被strip()的字符串在左右邊包含任意一個該set中的字符,都會被strip()掉。
s = 'hello word'
s.strip('hello')
s.strip('helo')
s.strip('hloe')
...(這是set無序,不重復性質)
得到的結果都一樣--->' word'
2、字符串相加:就是使用‘+’由于很簡單就不多說了。
3、字符串的查詢
使用index(),find()查詢,找到了返回下標。find()找不到不會報錯,index()找不到會報錯。
s = 'prince with rose'
>>> s.index('p')
>>> s.find('p')
>>> 0 # 返回的是該元素在字符串中的下標
>>>s.index('d')
>>>ValueError: substring not find
>>> s.find('d')
>>> -1 # 如果找不到返回'-1'
使用in / not in, 返回布爾值
# 存在時的情況
>>> 'prince' in s
>>> True
# 不存在時候的情況
>>> 'hello' in s
>>> False
4、字符串的比較
str.cmp():比較兩個對象,并根據結果返回一個整數。X< Y,返回值是負數 ,X>Y 返回的值為正數,X=Y,返回值為0。
python3已經沒有該方法,官方文檔是這么寫的:
The cmp() function should be treated as gone, and the cmp() special method is no longer supported. Use lt() for sorting, eq() with hash(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)
大意就是不再支持cmp()函數,如果你真的需要cmp()函數,你可以用表達式(a > b) - (a < b)代替cmp(a,b)
# 數字大小很好理解
>>> a= '100'
>>> b= '80'
>>> cmp(a,b)
>>>1
# 字符串的大小,可以理解為26個字母越排在后面的越大
>>> a= 'abc'
>>> b= 'efg'
>>> cmp(a,b)
>>> -1
# 相等的情況
>>> cmp(a,a)
>>> 0
5、字符串的長度
使用len()這個方法,s.len()就可以獲取到字符串的長度,返回的是一個整數。
6、字符串的大小寫(upper,lower)
up和low的比較級單詞
s = 'Hey gUys '
# 變大
u = s.upper()
u = 'HEY GUYS'
# 變小
l = s.lower()
l = 'hey guys'
s.swapcase() # 大小寫互換
>>> 'hEY GuYS'
s.capitalize() # 首字母大寫
>>> 'Hey guys'
# 帶有"_"的可以把連接的兩個單詞的首字母
s = 'hey_guys'
>>> s.capitalize()
>>> 'Hey_Guys'
7、字符串的測試、判斷函數,這些函數返回的都是bool值
S.startswith() # 是否以開頭
S.endswith() # 以結尾
S.isalnum() # 是否全是字母和數字,并至少有一個字符
S.isalpha() # 是否全是字母,并至少有一個字符
S.isdigit() # 是否全是數字,并至少有一個字符
S.isspace() # 是否全是空白字符,并至少有一個字符
S.islower() # S中的字母是否全是小寫
S.isupper() # S中的字母是否便是大寫
S.istitle() # S是否是首字母大寫的
8、字符串切片
str = '0123456789′
str[0:3] #截取第一位到第三位的字符
str[:] #截取字符串的全部字符
str[6:] #截取第七個字符到結尾
str[:-3] #截取從頭開始到倒數第三個字符之前
str[2] #截取第三個字符
str[-1] #截取倒數第一個字符
str[::-1] #創造一個與原字符串順序相反的字符串
str[-3:-1] #截取倒數第三位與倒數第一位之前的字符
str[-3:] #截取倒數第三位到結尾
str[:-5:-3] #逆序截取,截取倒數第五位數與倒數第三位數之間
9、字符串替換
python 字符串替換可以用2種方法實現:
1是用字符串本身的方法。
2用正則來替換字符串
#1.用字符串本身的replace方法
a = 'hello world'
a.replace('world','python')
>>> a
>>> hello python
2.用正則表達式來完成替換:
import re
b = str.sub(r'word$','python',a) # 至少傳三個參數:r'', 替換內容,被替換的字符串
>>> b
>>> hello python