新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Python字符串操查找替換分割和連接方的法及使用
str提供了如下常用的執(zhí)行查找、替換等操作的方法:

startswith():判斷字符串是否以指定子串開頭。
endswith():判斷字符串是否以指定子串結(jié)尾。
find():查找指定子串在字符串中出現(xiàn)的位置,如果沒有找到指定子串,則返回 -1。
index():查找指定子串在字符串中出現(xiàn)的位置,如果沒有找到指定子串,則引發(fā) ValueError 錯誤。
replace():使用指定子串替換字符串中的目標(biāo)子串。
translate():使用指定的翻譯映射表對字符串執(zhí)行替換。
如下代碼示范了上面方法的用法:
s = 'crazyit.org is a good site'
# 判斷s是否以crazyit開頭
print(s.startswith('crazyit'))
# 判斷s是否以site結(jié)尾
print(s.endswith('site'))
# 查找s中'org'的出現(xiàn)位置
print(s.find('org')) # 8
# 查找s中'org'的出現(xiàn)位置
print(s.index('org')) # 8
# 從索引為9處開始查找'org'的出現(xiàn)位置
#print(s.find('org', 9)) # -1
# 從索引為9處開始查找'org'的出現(xiàn)位置
print(s.index('org', 9)) # 引發(fā)錯誤
# 將字符串中所有it替換成xxxx
print(s.replace('it', 'xxxx'))
# 將字符串中1個it替換成xxxx
print(s.replace('it', 'xxxx', 1))
# 定義替換表:97(a)->945(α),98(b)->945(β),116(t)->964(τ),
table = {97: 945, 98: 946, 116: 964}
print(s.translate(table)) # crαzyiτ.org is α good siτePython字符串分割、連接方法
Python 還為 str 提供了分割和連接方法:
split():將字符串按指定分割符分割成多個短語。
join():將多個短語連接成字符串。
下面代碼示范了上面兩個方法的用法:
s = 'crazyit.org is a good site'
# 使用空白對字符串進(jìn)行分割
print(s.split()) # 輸出 ['crazyit.org', 'is', 'a', 'good', 'site']
# 使用空白對字符串進(jìn)行分割,最多只分割前2個單詞
print(s.split(None, 2)) # 輸出 ['crazyit.org', 'is', 'a good site']
# 使用點(diǎn)進(jìn)行分割
print(s.split('.')) # 輸出 ['crazyit', 'org is a good site']
mylist = s.split()
# 使用'/'為分割符,將mylist連接成字符串
print('/'.join(mylist)) # 輸出 crazyit.org/is/a/good/site
# 使用','為分割符,將mylist連接成字符串
print(','.join(mylist)) # 輸出 crazyit.org,is,a,good,site 文章題目:創(chuàng)新互聯(lián)Python教程:Python字符串操查找替換分割和連接方的法及使用
當(dāng)前網(wǎng)址:http://m.fisionsoft.com.cn/article/cocccje.html


咨詢
建站咨詢
