Python 基本數據類型 (二) - 字符串1
阿新 • • 發佈:2019-01-12
程序 pri alex 寬度 體系 小寫 空格 位置 序列
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 5V2 = 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
Python 基本數據類型 (二) - 字符串1