字串的各種方法和案例

來源:互聯網
上載者:User
本篇文章主要介紹字串的各種方法和案例,感興趣的朋友參考下,希望對大家有所協助。

代碼如下:

'''字串:是以單引號或雙引號括起來的任意文本,‘abc’"def"字串不可變'''#建立字串str1 = "sunck is a good man!"str2 = "sunck is a nice man!"#字串運算#字串串連,字串不可變str3 = "sunck"str4 = "is a man"str5 = str3 + str4print(str5)#輸出重複字串str6 = "hello"str7 = str6 * 3print(str7)#訪問字串中的某一個字元#通過索引下標尋找字元,從0開始   字串名[下標]str8 = "sunck is a nice man!"print(str8[1])#截取字串,包含前面的6,不包含15[6,15),str9 = "sunck is a nice man!"str10 = str9[6:15]str11 = str9[:6]#從頭截取str12 = str9[16:]#從給定下標處截取到最後print(str10)#判斷有沒有需要的字元str13 = "sunck is a nice man!"print("good" in str13)#falseprint("good" not in str13)#true#格式化輸出num = 10print("num = %d" % (num))#%d預留位置, num替換%d,%d表示整數str14 = "sunck is a nice man!"f = 3.14print("str14 = %s\nf = %.3f" % (str14,f))#字串替換用%s代替,浮點用%f表示(%.3f 精確到小數點後三位,會四捨五入)#\n換行#逸出字元'''\:將一些字元轉換成有特殊含義的字元\\:表示一個“\”\t:定位字元(四個空格)r:如果字串裡有好多字串都需要轉義,允許用r表示內部的字串預設不轉義'''print("hello \\ world")print('hello \'world\'')print("hello 'world'")#如果字串內有很多換行,用\n不好閱讀print('''helloworld''')#三引號可以換行print("hello\tworld")#列印\\\t\\print(r"\\\t\\")#eval()'''功能:將字串str當成有效運算式來求值,並返回計算結果'''num1 = eval("123")#轉為整數print(eval("1+23"))#自動計算,字母不可計算#len(str)'''返回字串的長度'''print(len("hello world"))#長度看字元個數#str.lower'''轉換字串中的大寫字母為小寫字母'''str15 = "suncK is a good man"print(str15.lower())#str.upper()  轉換字串中的小寫字母為大寫字母str16 = "suncK is a good man"print(str16.upper())#str.swapcase 轉換字串中大寫字母為小寫字母,小寫字母為大寫字母。print("suncK is a good man".swapcase())#str.capitalize() 首字母大寫print("suncK is a good man".capitalize())#str.title() 每個單詞的首字母大寫print("suncK is a good man".title())#center(width[,fillchar])#返回一個指定寬度的置中字串,fillchar為填充的字串(預設空格填充)print("suncK is a good man".center(40,"*"))#ljust(width[,fillchar])#返回一個指定寬度的靠左對齊字串,fillchar為填充的字串(預設空格填充)print("suncK is a good man".ljust(40),"%")#rjust(width[,fillchar])#返回一個指定寬度的靠右對齊字串,fillchar為填充的字串(預設空格填充)print("suncK is a good man".rjust(40),"%")#zfill(width)#返回一個長度為width的字串,原字串靠右對齊,前面補0。print("suncK is a good man".zfill(40))#count(str[,start][,end])#返回str字串中str的出現的次數,可以指定一個範圍,預設全部print("suncK is a good good man".count("good",15,len("suncK is a good good man")))#find(str[,start][,end])#從左至右,檢測str字串是否包含在字串中,可以指定範圍,預設從頭到尾,#返回的是第一次開始的下標,沒有返回-1print("suncK is a good good man".find("good"))print("suncK is a good good man".find("good",15,len("suncK is a good good man")))#rfind(str[,start][,end])#從右向左檢測print("suncK is a good good man".rfind("good"))#index(str,start = 0,end = len(str))#跟find方法基本一樣,如果str不存在會報異常print("suncK is a good good man".index("good"))#rindex(str,start = 0,end = len(str))#與rfind方法一樣,當不存在時會報異常print("suncK is a good good man".rindex("good"))#lstrip()#截掉字串左側指定字元,預設空格print("*suncK is a good good man".lstrip("*"))#rstrip()#截掉字串右邊的字元,預設空格print("*suncK is a good good man*".rstrip("*"))#strip()#截掉兩邊的指定內容,預設空格print("**suncK is a good good man**".strip("*"))str17 = "a"print(ord(str17))#輸出ASCII值#字串比較大小#從第一個字元開始比較,誰的ASCII的值大就大,如果相等#就比較下一個字元,誰的值大誰就大print("mszzz" < "ms") # \0 ASCII:0#split(str = "",num) 以str為分隔字元截取字串,指定num,則僅截取num個字元str18 = "sunck  is     good   man"list1 = str18.split(" ")#print(str18.split(" ",3))c = 0for s in list1:    if len(s) > 0:        c += 1print(c)#splitlines(keepends)  按照(\r, \r\n, \n)分割,返回一個作為#keepends == True 會保留分行符號,預設false(不保留分行符號)str19 = '''sunck is a good man!sunck is a nice man!'''print(str19.splitlines(True))#true帶著分行符號輸出#join() 以一個特定的字串分隔符號,將seq中的所有元素組合成一個字串list2 = ['sunck','is','a','good','man']str20 = " ".join(list2)print(str20)#max() min()str21 = "sunck is a good man z"print(max(str21))print(min(str21))#replace(oldstr,newstr,count)# 用newstr替換oldstr,預設全部替換,如果制定了count,那隻替換count個str22 = "sunck is a good man"str23 = str22.replace("good","nice",1)#good要替換的單詞,nice替換成,1替換第幾個print(str23)#maketrans() 建立字串的映射表'''oldstr要轉換的字串newstr要轉換的字串'''t24 = str.maketrans("sunck","kaige")#將s對應成k,以此類推str25 = "sunck is a good man"str26 = str25.translate(t24)print(str26)#startswith(str,start = 0,end = len(str))#判斷是否以str開頭str27 = "sunck is a good man "print(str27.startswith("sunck",5,16))#endswith(str,start = 0,end = len(str))#在給定的範圍內判斷是否已給定的字串開頭,如果沒有指定範圍,預設整個字串str28 = "sunck is a good man "print(str28.endswith("man"))#encode(encoding="utf-8",errors="strict")#編碼#str29 = "sunck is a good man"str29 = "sunck凱 is a good man"data30 = str29.encode("utf-8","ignore")#ignore 忽略錯誤print(data30)#解碼  注意:要與編碼時的編碼格式一致str31 = data30.decode("utf-8")print(str31)#isalpha() 如果字串中至少一個字元且所有的字元都是字母返回True#f否則為falsestr32 = "sunck is a good man"print(str32.isalpha())#isalnum()#如果字串中至少有一個字元且所有的字元都是字母或數字返回true#否則返回falsestr33 = "123"print(str33.isalnum())#isupper()#如果字串中至少有一個英文字元且所有的字元都是大寫的英文字母返回true,否則返回falseprint("ABC".isupper())#返回Trueprint("ABC1".isupper())#返回Trueprint("1".isupper())#返回falseprint("acn".isupper())#返回falseprint("ABC#".isupper())#返回true#islower()#如果字串中至少有一個英文字元且所有的字元都是小寫英文字母返回trueprint("abc".isupper())#返回Trueprint("abc1".isupper())#返回Trueprint("1".isupper())#返回falseprint("ABC".isupper())#返回falseprint("abc#".isupper())#返回true#istitle()#如果字串是標題化的返回True,否則返回falseprint("sunck is".istitle())#返回falseprint("Sunck Is".istitle())#返回True#isdigit()#如果字串只包含數字字元,返回true,否則返回falseprint("123".isdigit())#返回trueprint("123a".isdigit())#返回false#isnumeric()#如果字串只包含數字字元,返回true,否則返回falseprint("123".isdigit())#返回trueprint("123a".isdigit())#返回false#isdecimal()##如果字串只包含10進位字元,返回true,否則返回falseprint("123".isdigit())#返回trueprint("123a".isdigit())#返回false##如果字元中只包含空格返回True,否則返回falseprint(" ".isspace())print("\t".isspace())#Trueprint("\n".isspace())#trueprint("\r".isspace())#true

總結:以上就是本篇文的全部內容,希望能對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.