字符串定義:
變量 = “值”
學習中記錄了相關字符串操作命令,以下命令可以直接運行查看結果。
name = "abcdefABCDEF" print(name[5]) print(name[len(name)-1]) print(name[-1]) print(name[2:]) #從開始到結束 print(name[2:-1:2]) #跳一個取一個值 print(name[-1::-1]) #倒序1 print(name[-1:0:-1]) #倒序2 print(name[::-1]) #倒序3 mystr = "hello world yangyang and yangxxxx" print(mystr.find("world")) #顯示出第一個元素出現的下標 print(mystr.find("321321")) #如果沒有該元素則顯示-1 print(mystr.find("yang")) print(mystr.rfind("yang")) #默認從左向右找,rfind爲從右向左找 print(mystr.index("yang")) print(mystr.rindex("yang")) #print(mystr.index("dsadsadas")) #沒有找到時,程序異常報錯 print(mystr.count("yang")) #返回字符在字符串中出現的個數 print(mystr.replace("world","WORLD")) #替換元素 print(mystr.replace("yang","zhang",2)) #最後的參數是替換幾個 print(mystr.split(" ")) #按照空格進行切割 ['hello', 'world', 'yangyang', 'and', 'yangxxxx'] print(mystr.capitalize()) #字符串首字母大寫 print(mystr.title()) #字符串中每個單詞的首字母大寫 print(mystr.endswith("xx")) #查看字符串末尾的字符 print(mystr.startswith("hello")) #查看字符串首字符 print(mystr.lower()) #字符串全部改成小寫 print(mystr.upper()) #字符串全部改成大寫 print(mystr.center(50)) #居中對齊 print(mystr.ljust(50)) #靠左對齊 print(mystr.rjust((50))) #靠右對齊 print("----") test = mystr.center(50) print(test.lstrip()) #刪除左邊的空格或者字符 print(test.rstrip()) #刪除右邊的空格或者字符 print(test.strip()) #刪除兩邊的空格或者字符 print(mystr.partition("yang")) #以yang爲中間字符左右兩邊成爲單獨的字符串 print(mystr.rpartition("yang")) #功能同上從右邊開始算起 mystr2 = "hello\nworld\nyangyang\nand\nyangxxxx" print(mystr2) print(mystr2.splitlines()) #根據換行符(\n)分割字符串 ['hello', 'world', 'yangyang', 'and', 'yangxxxx'] mystr.isalpha() #識別字符串中是否爲字母 mystr.isdigit() #識別字符串中是否爲數字 mystr.isalnum() #識別字符串中既有數字也有字母 mystr.isspace() #識別字符串中是否爲純空格 print("-----------") mystr3 = mystr2.splitlines() b = "-" print(b.join(mystr3)) #以-爲連接符把字符串中的每個元組都連接起來 #把下面字符串中的空格和\t全部進行切割再組合 #----------------------------------- test = "haha \t nihao a \t ni shi wo de hao \t pengyou" print(test.split()) #如果split()中什麼都不寫的話,默認切割\t 空格 \n 等 print(test.split(" \t")) #表示只切割“空格+\t”的字符 test1 = test.split() print("".join(test1)) #再組合! #------------------------------------