Python字串 – 在本文中,我將向你展示在Python程式設計中, 字串普遍都會使用的4大類19方法,
- python 尋找 (python index, python find, python rfind)
- python 擷取 (python slicing)
- python 對比 (python contains (in), python startsWith, python endsWith, python equals (==))
- python 換成大小寫 (python upper, python lower, python capitalize, python swapcase).
現在開始Python string 編程教學. Go!
方法 | 例子: |
搜查的關键字是否存在於字串中1: if value in String: continue if “要搜查的關键句” in String: continue | str = “I believe I can fly”; print(“believe” in str) # True |
搜查的關键字是否存在於字串中2(由前到後): String.find(value) String.find(“ 要搜查的關键句”) | str = “I believe I can fly. I believe!”; print(str.find(“believe”)) # 2 print(str.find(“cannot”)) # -1 |
搜查的關键字是否存在於字串中2 (由後到前): String.rfind(value) String.rfind(“ 要搜查的關键句”) | str = “I believe I can fly. I believe!”; print(str.rfind(“believe”)) # 23 print(str.rfind(“cannot”)) # -1 |
搜查的關键字位於字串中的第幾個字元(由前到後): String.index(String); String.index(“要搜查的關键句”); *若回傳值”-1″, 即是找不到. | str = “I believe I can fly. I believe!”; print(str.index(“believe”)) # 2 print(str.index(“cannot”)) # ValueError: substring not found |
搜查的關键字位於字串中的第幾個字元 (由後到前): String.rindex(String); String.rindex(“要搜查的關键句”); *若回傳值”-1″, 即是找不到. | str = “I believe I can fly. I believe!”; print(str.rindex(“believe”)) # 23 print(str.rindex(“cannot”)) # ValueError: substring not found |
搜查的關键字是否存在於字串的開端: String.startswith(String); String.startswith(“要搜查的關键句”); | str = “I believe I can fly. I believe”; print(str.startswith(“I”)) # True print(str.startswith(“believe”)) # False |
搜查的關键字是否存在於字串的尾端: String.endswith(String); String.endswith(“要搜查的關键句”); | str = “I believe I can fly. I believe”; print(str.endswith(“I”)) # False print(str.endswith(“believe”)) # True |
撷取字串: string[start:end] Start:由第幾個字元開始撷取 End: 要撷取多少個字 | str = “I believe I can fly”; print(str[3: 7]) # elie |
字串對比 (包含大小寫對比): String == String; String == “要對比的字串”; | str1 = “I believe I can fly”; str2 = “i believe i can fly”; str3 = “I believe I can fly”; print(str1== str2); # False print(str1== str3); # True |
字串組合 String + “要組合的字串”; | str1 = “Hello “; str2 = “World”; print(str1 + str2) # Hello World |
查字串長度 len(String) len(“要查長度的字串”) | str = “I believe I can fly”; len(str) |
句子中第一個字成大寫 string.capitalize() | str = “i believe i can fly”; print (str.capitalize()); # I believe i can fly |
全部變成小寫 string.lower() | str = “i believe I CAN FLY”; print (str.lower()); # i believe i can fly |
全部變成大寫 string.upper() | str = “i believe I CAN FLY”; print (str.upper()); # I BELIEVE I CAN FLY |
把String中的大寫變小寫, 小寫變為大寫 string.swapcase() | str = “i believe I CAN FLY”; print (str.swapcase()); # I BELIEVE i can fly |
相關頁面:
Python字串 – 字串String功能速查表 – 尋找,擷取,對比,換成大小寫
Python字串 – String功能速查表 – 查詢字串資料普遍都會使用的11方法