Python學習之路-string字符串的常用方法
阿新 • • 發佈:2018-02-20
sta with abs art nds tab isl ket itl
大小寫轉換
1 __author__ = "KuanKuan" 2 print("name is JankinYu".capitalize())#轉為首字母大寫 3 print("name is JankinYu".title())#轉為標題形式 Name Is Jankinyu 4 print("NAMW".lower())#轉換為小寫 5 print("name".upper())#轉換為大寫 6 print("Name".swapcase())#大寫變小寫小寫變大寫 7 """ 8 輸出結果: 9 Name is jankinyu 10 Name Is Jankinyu11 namw 12 NAME 13 nAME 14 """
字符串判斷
1 __author__ = "KuanKuan" 2 print("name is JankinYu".startswith("name")) # 以...開頭 如果正確則為True 3 print("name is JankinYu".endswith("JankinYu"))#以...結尾 如果正確則為True 4 print("asd".isalpha())#如果是字母則為True 5 print("123".isdigit())#如果是數字則為True 6 print("asd123".isalnum())#如果是數字或者字母則為True 7 print("jjk".isidentifier())#判斷是否為合法變量名合法為True 8 print(" ".isspace()) # 空格 -->True 9 print("My Name Is Jankinyu".istitle()) # 標題 -->True 10 print("My Name Is Jankinyu".isprintable()) # 可打印 tty file, drive file -->True 11 print("A".isupper()) # 大寫 -->True 12 print("a".islower()) # 小寫 -->True
輸出顯示
1 __author__ = "KuanKuan" 2 print(",".join(["1", "2", "3"])) # 連接 3 # ->1,2,3 4 print("name is JankinYu".split()) # 拆分為列表,默認拆分符為空格 5 # ->[‘name‘, ‘is‘, ‘Alex‘] 6 print("name\n is\r\n JankinYu".splitlines()) # 拆分為列表,默認拆分符為回車 7 # ->[‘name‘, ‘ is‘, ‘ Alex‘] 8 print("name".center(50, "-")) # 內容居中,兩側填充 9 # ->-----------------------name----------------------- 10 print("name".ljust(50, "*")) # 內容靠左,以*填充 11 # ->name********************************************** 12 print("name".rjust(50, "-")) # 內容靠右,以-填充 13 # ->----------------------------------------------name 14 print("name".zfill(50)) # 內容靠右,以0填充 15 # ->0000000000000000000000000000000000000000000000name 16 print("name is\t JankinYu".expandtabs(tabsize=18)) # 設置‘\t‘寬度 17 # ->name is JankinYu 18 print("I am from {city},and {year} years old".format(city="kuankuan", year=18)) # 格式化 19 # ->I am from Wuhan,and 18 years old 20 print("I am from {city},and {year} years old".format_map({"city": "kuankuan", "year": 18})) # 字典參數格式化 21 # ->I am from Wuhan,and 18 years old 22 print("\nname".lstrip()) # 去除左側回車和空格 ->name 23 print("name\n".rstrip()) # 去除右側回車和空格 ->name 24 print(" name\n".strip()) # 去除兩側回車和空格 ->name 25 print("~~~~~~~~~~~~~~~~~~~~")
查找替換
1 __author__ = "KuanKuan" 2 p = str.maketrans("abc", "123") # 創造翻譯字典 3 print(type(p)) # --><class ‘dict‘> 4 print("abc".translate(p)) # 翻譯,參數:dict -->123 5 print("name is JankinYu".replace("n", "N")) # 替換 -->Name is JankinYu 6 print("name is JankinYu".count("i")) # 字符計數 -->2 7 print("name is JankinYu".find("n")) # 查找,返回下標,沒有則返回-1 -->2 8 print("name is JankinYu".rfind("n")) # 右邊開始查找 -->13 9 print("name is JankinYu".index("n")) # 返回索引,不存在則報錯 -->0 10 print("name is JankinYu".rindex("n")) # 右邊開始查找 -->13 11 """ 12 輸出結果: 13 <class ‘dict‘> 14 123 15 Name is JaNkiNYu 16 2 17 0 18 13 19 0 20 13 21 """
Python學習之路-string字符串的常用方法