python學習筆記之基礎操作(二)字符串操作(2)

#二:替換操作
#replace():替換指定字符串
test = "123abcefsdfa"
print(test.replace("123","___"))

___abcefsdfa
#swapcase():轉換大小寫:
test = "asdfgVBNMK"
print(test.swapcase())
ASDFGvbnmk
#upper(),lower()
print(test.upper())
print(test.lower())
ASDFGVBNMK
asdfgvbnmk
#三,分割操作
#split():按照指定字符串分割字符,可以指定分割的數量
test = "123,456,789"
print(test.split(","))
print(test.split(",",1))
['123', '456', '789']
['123', '456,789']
#partition()按照指定字符串分割爲兩部分,包含分隔符
#rpartition(),右面第一個開始分割
print(test.partition(","))
print(test.rpartition(","))
('123', ',', '456,789')
('123,456', ',', '789')
#四:查找操作
#find():找不到返回-1
test = "12345672"
print(test.find("2"))
print(test.rfind("2"))
print(test.find("a"))
1
7
-1
#index同上,不過返回錯誤找不到的話
print(test.index("2"))
print(test.rindex("2"))
print(test.index("a"))
1
7



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

ValueError                                Traceback (most recent call last)

<ipython-input-17-af7b2106d969> in <module>()
      2 print(test.index("2"))
      3 print(test.rindex("2"))
----> 4 print(test.index("a"))


ValueError: substring not found
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章