標籤:
字串
- 內建操作
- 字串長度
- 大小寫變換
- 去空格或其他
- 連接字串
- 尋找替換
- 分割
- 判斷
內建操作字串長度
代碼
s = ‘abcd‘print len(s)
大小寫變換
lower 小寫
upper 大寫
swapcase 大小寫互換
capiatlize 首字母大寫
代碼
s = ‘aBcd‘print s.lower()print s.upper()print s.swapcase()print s.capitalize()
去空格或其他
strip 截掉左右空格或左右其他字元
lstrip 截掉左空格或左右其他字元
rstrip 截掉右空格或左右其他字元
代碼
# 去空格斷行符號s = ‘ abcd \n‘print s.strip() # abcdprint s.lstrip() # abcd \nprint s.rstrip() # abcd# 去特定字元s = ‘abcda‘print s.strip(‘a‘) # bcdprint s.lstrip(‘a‘) # bcdaprint s.rstrip(‘a‘) # abcd
連接字串
代碼
# 直接連接s = ‘abc‘print s + ‘defg‘# 串連多個字串strs = [‘a‘, ‘b‘, ‘c‘, ‘d‘] # 要串連的字串數組sep = ‘,‘ # 字串之間的分隔字元s = sep.join(strs) # 串連print s # 輸出 a,b,c,d
尋找替換
find 返回出現的第一個標號,沒有找到則返回-1。
index 與find一樣,但在沒有找到時會拋出異常。
rfind 返回最後出現的第一個標號,沒有找到則返回-1。
rindex 與rfind相同,但在沒找到時會拋出異常。
count 統計字串出現次數。
replace 替換字串
代碼
# 尋找s = ‘abcdefgabcdefg‘print s.find(‘e‘) # 4print s.index(‘e‘) # 4print s.rfind(‘e‘) # 11print s.rindex(‘e‘) # 11print s.count(‘e‘) # 2# 特定範圍尋找print s.find(‘e‘, 5, 7) # -1 尋找範圍s[5:7]print s.index(‘e‘, 5) # 11 尋找範圍s[5:]print s.rfind(‘e‘, 5, 7) # -1 尋找範圍s[5:7]print s.rindex(‘e‘, 0, 5) # 4 尋找範圍s[0:5]# 替換字串print s.replace(‘a‘, ‘z‘) # ‘zbcdefgzbcdefg‘# 限定替換次數print s.replace(‘a‘, ‘z‘, 1) # ‘zbcdefgabcdefg‘ 1為替換次數
分割
代碼
# 全部分割 s = ‘a, b, c, d, e‘print s.split(‘,‘) # [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]# 分割前n個print s.split(‘,‘, 2) # [‘a‘, ‘b‘, ‘c,d,e‘] 分割前2個 2為次數
判斷
isalnum 判斷是否只包含字母或數字
isalpha 判斷是否只包含字母
isdigit 判斷是否只包含數字
isdecimal 判斷是否只包含十進位數
isnumeric 判斷是否只包含數字字元
isspace 判斷是否只包含空格
istitle 判斷是否是標題化的
isupper 判斷是否都是大寫
islower 判斷是否都是小寫
代碼
s = ‘abc‘print s.isalpha()# ...
本站文章為 寶寶巴士 SD.Team 原創,轉載務必在明顯處註明:(作者官方網站: 寶寶巴士 )
轉載自【寶寶巴士SuperDo團隊】 原文連結: http://www.cnblogs.com/superdo/p/4579225.html
[Python基礎]007.字串