python字符串的常見處理方法
方法 | 使用說明 | 方法 | 使用說明 |
string[start:end:step] | 字符串的切片 | string.replace | 字符串的替換 |
string.split | 字符串的分割 | sep.jojin | 將可迭代對象按sep分割符拼接為字符串 |
string.strip | 刪除首尾空白 | string.lstrip | 刪除字符串左邊空白 |
string.rstrip | 刪除字符串右邊的空白 | string.count | 對字符串的字串計數 |
string.index | 返回子串首次出現的位置 | string.find | 返回字串首次出現的位置(找不到返回-1) |
string.startswith | 字符串是否以什么開頭 | string.endswith | 字符串是否以什么結尾 |
代碼示例說明:
tel='13612345678'
print(tel.replace(tel[3:7],'****')) out:136****5678
print('12345@qq.com'.split('@')) out:['12345','qq.com'] #以@為字符串的分割點
print('-'.join('Python')) out:P-y-t-h-o-n #以‘-’號為連接符,將Python按單個字符分開連接
print(" 今天是星期日 ".strip()) out:今天是星期日 #首尾空白均已經刪除
print(" 今天是星期日 ".lstrip()) #刪除左邊空白
print(" 今天是星期日 ".rstrip()) #刪除右邊空白
string5 = '中國方案引領世界前行,展現了中國應勢而為,勇於擔當的作用!'
print(string5.count('中國')) out:2
string6 = '我是一名Python用戶,Python給我的工作帶來了很多便捷。'
print(string6.index('Python')) out:4 #index方法只要匹配到第一個index后就會停止,並把位置返回,因此得到的結果是4,如果沒找 到返回報錯信息
print(string6.find('Python')) out: 4 #find 方法用於匹配的時候,跟上面的index形式差不多 返回的是要查的字符串首次出現所在的位置
如果沒有找到返回 -1(推薦使用,就算沒有找到也不會影響其他程序運行) 這個地方跟 index有 點不同
string7 = '2017年匆匆走過,迎來嶄新的2018年'
print(string7.startswith('2018年')) out:False 字符串是否以“2018年”開頭
print(string7.endswith('2018年')) out:True 字符串是否以“2018年”結尾