#coding=utf-8 __author__ = 'Administrator' # 字符串處理函數 s1 = "study python string function , I love python" #獲取字符串長度 print(len(s1)) #將字符串所有轉換爲大寫 print(s1.upper()) #將字符串所有轉換爲小寫 print(s1.lower()) #將字符串中大寫轉小寫,小寫轉大寫 print(s1.swapcase()) s2 = "python is ok" #獲取固定長度,右對齊,右邊不夠用空格補齊 print(s2.ljust(30)) #獲取固定長度,左對齊,左邊不夠用空格補齊 print(s2.rjust(30)) #獲取固定長度,中對齊,中間不夠用空格補齊 print(s2.center(30)) #獲取固定長度,右對齊,右邊不夠用0補齊 print(s2.zfill(30)) #搜索指定字符串,沒有返回-1,有的話返回下表開始的位置 #s1.find("要搜索的字符串",start(可選,起始位置),end(可選,結束位置)) print(s1.find("python")) print(s1.find("python",8,len(s1))) #從右邊開始搜索 print(s1.rfind("python")) #統計該字符串出現的次數 print(s1.count("p")) #s1.index()g跟find()方法同樣,只是查不到會拋異常 print(s1.index("python")) #字符串替換的一些方法 #t替換s1中的love爲like print(s1.replace("love","like")) #替換s1中的python爲scala,最後一個參數爲替換的次數 print(s1.replace("python","scala",2)) #字符串去空格以及去指定字符 s3 = " i love python " #去兩邊空格 print(s3.strip()) #去左邊空格 print(s3.lstrip()) #去右邊空格 print(s3.rstrip()) s4 = "i love python" #去兩邊字符串 print(s4.strip("i")) #去左邊字符串 print(s4.lstrip("i")) #去右邊字符串 print(s4.rstrip("python")) #按指定字符分割字符串爲數組 print(s1.split(" ")) #字符串判斷相關 ,一下返回值全是True或者False #是否以study開頭 print(s1.startswith("study")) #是否以python結尾 print(s1.endswith("python")) #是否全爲字母或數字(要麼全是字母,要麼全是數字) print(s1.isalnum()) #是否全爲字母 print(s1.isalpha()) #是否全爲數字 print(s1.isdigit()) #是否全是小寫 print(s1.islower()) #是否全是大寫 print(s1.isupper()) #s1的首字母是不是大寫 print(s1.istitle()) #編解碼 #解碼函數 print(type(s1)) s5 = s1.decode("utf-8") print(type(s5)) #編碼函數 s6 = s1.encode("utf-8") print(type(s6)) #cmp函數用於比較兩個對象s1<s2返回-1,s1>s2返回1 s1=s2返回0 print(cmp(s1,s2))