Python 基本資料型別 (二) - 字串1
阿新 • • 發佈:2019-01-11
1 # ----------- 首字母大寫 ---------- 2 test = "alex is a man" 3 v = test.capitalize() 4 print(v): Alex is a man
1 # ----------- 轉換全部字串為小寫 ---------- 2 test = "aLex is A man" 3 V1 = test.casefold() #更加強大,可以處理其他語言體系 4 print(V1) # alex is a man 5 V2 = test.lower() #只處理英文字元 6 print(V2) # alex is a man
1 # ----------- 設定寬度,並將內容居中 ---------- 2 # 20 代表總長度,如果小於字串本身長度,則忽略 3 # '+' 表示填充的內容,預設為填充空格,只能為單字元(支援中文) 4 test = "aLex is A man" 5 V1 = test.center(20) 6 print('*'+V1+'*') # * aLex is A man * 7 V2 = test.center(20,'+') 8 print('*'+V2+'*') # *+++aLex is A man++++*
1# ----------- 去字串中尋找子序列出現的次數 ---------- 2 # 從第5個位置(包括5)開始往後找,預設為從0找起 3 # 直到第14個位置(不包括14)結束,預設找到末尾 4 test = "aLexisAmanAlexALex" 5 V1 = test.count('ex') 6 print(V1) # 3 7 V2 = test.count('ex',5, 14) 8 print(V2) # 1
1 # ----------- 判斷是否以特定字串結尾/開始 ---------- 2 test = "aLex is A man" 3 V1 = test.endswith('a') 4 print(V1) # False 5 V2 = test.endswith('an') 6 print(V2) # True 7 V1 = test.startswith('a') 8 print(V1) # True 9 V2 = test.startswith('an') 10 print(V2) # False
1 # ----------- 從開始往後找,找到第一個後,獲取其位置 ---------- 2 # 返回第一個找到的字串下標,找不到則返回-1 3 # 對於查詢區間滿足左閉後開的原則 4 test = "aLexaLexaLex" 5 V1 = test.find("ex") 6 print(V1) # 2 7 V2 = test.find("ex",4,7) 8 print(V2) # -1 9 V3 = test.find("ex",4,8) # 4<= 查詢位置<8 10 print(V3) # 6
1 # ----------- 格式化1,將字串中的佔位符替換為指定的值 ---------- 2 # 按照佔位符名稱替換 3 test = "I am {name},age {a}" 4 print(test) # I am {name},age {a} 5 V1= test.format(name='Alex',a=19) 6 print(V1) # I am Alex,age 19 7 8 # ----------- 格式化2,將字串中的佔位符替換為指定的值 ---------- 9 # 按照數字順序替換 10 test = "I am {0},age {1}" 11 print(test) # I am {0},age {1} 12 V1= test.format('Alex',19) 13 print(V1) # I am Alex,age 19
1 # ----------- 格式化3,將字串中的佔位符替換為指定的值 ---------- 2 # 按照佔位符名稱替換, 字典鍵值對方式傳值 3 test = "I am {name},age {a}" 4 print(test) # I am {name},age {a} 5 V1= test.format_map({"name":"alex","a":19}) 6 print(V1) # I am Alex,age 19
1 # ----------- 從開始往後找,找到第一個後,獲取其位置 ---------- 2 # 返回第一個找到的字串下標,找不到則程式報錯,終止執行 (與find函式的區別) 3 # 對於查詢區間滿足左閉後開的原則 4 test = "aLexaLexaLex" 5 V1 = test.index("ex") 6 print(V1) # 2 7 V2 = test.index("8") # 程式報錯 8 print(V2)
1 # ----------- 字串中是否只包含字母和數字 ---------- 2 # 如果只包含字母和數字,則返回True 3 test = "Alex123+124" 4 V1 = test.isalnum() 5 print(V1) # False 6 test = "Alex123124" 7 V2 = test.isalnum() 8 print(V2) # True