name = "zhangsan"isIn = name.find("an")print(isIn)
index()在字符串中查找指定的字符串,找不到時直接報錯:name = "zhangsan"isIn = name.index('h')print(isIn)name = "zhangsan"name1 = "zhangsan"isEq = name.__eq__(name1)print(isEq)name = "zhang san"name = name.split()print(name)name = "{} {} zhangsan" name = name.format('I', 'am')print(name)name = "zhangsan"name = '*'.join(name)print(name)
isalnum()判斷字符串是否包含字母數字字符:name = "zhangsan1"isTrue = name.isalnum()print(isTrue)
name = "zhangsan1*"isTrue = name.isalnum()print(isTrue)name = "zhangsan"isTrue = name.isalpha()print(isTrue)
name = "zhangsan1"isTrue = name.isalpha()print(isTrue)
startswith()判斷字符串以某個字符串開頭,返回boolean類型:name = "zhangsan"isTrue = name.startswith("zh")print(isTrue)
endswith()判斷字符串以某個字符串結尾,返回boolean類型:name = "zhangsan"isTrue = name.endswith("san")print(isTrue)1) re.match嘗試從字符串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match()就返回none。import re line="this hdr-biz 123 model server 456"pattern=r"123"matchObj = re.match( pattern, line)
2)re.search掃描整個字符串並返回第一個成功的匹配。import re line="this hdr-biz model server"pattern=r"hdr-biz"m = re.search(pattern, line)
3)Python 的re模塊提供了re.sub用於替換字符串中的匹配項。import re line="this hdr-biz model args= server"patt=r'args='name = re.sub(patt, "", line)
4)compile 函數用於編譯正則表達式,生成一個正則表達式( Pattern )對象,供 match() 和 search() 這兩個函數使用。import re pattern = re.compile(r'\d+')
5)re.findall 在字符串中找到正則表達式所匹配的所有子串,並返回一個import re line="this hdr-biz model args= server"patt=r'server'pattern = re.compile(patt)result = pattern.findall(line)
6)re.finditer和 findall 類似,在字符串中找到正則表達式所匹配的所有import re it = re.finditer(r"\d+","12a32bc43jf3")for match in it: print (match.group() )在 Python 字符串中如果顯示特殊字符,必須經過轉義才能夠顯示。例如,換行符需要使用 \n 表示,制表符需要使用 \t 表示,單引號需要使用 \' ,雙引號需要使用 \" 表示等等。>>> a = 'I\nlove\nU'>>> a'I\nlove\nU'>>> print(a)IloveU>>> print('aaabb\cccddd')aaabbcccddd編程中關於字符串大小寫轉換的情況,經常會遇到,這裡大概總結如下:
為了方便學習,先設定一個測試變量:a = 「gaoqi love programming, loveSXT」返回一個長度為width,兩邊用fillchar(單字符)填充的字符串。即字符串str居中,兩邊用fillchar填充。若字符串的長度大於width,則直接返回字符串str。
語法:str.center(width , "fillchar") -> str 返回字符串width:指定字符串長度;
fillchar:要填充的單字符,默認為空格;
str = "i love python"print(str.center(20,"*")) print(str.center(1,"*")) print(str.center(20,"8"))print(str.center(20))***i love python****i love python888i love python8888 i love python返回一個原字符串左對齊,並使用fillchar填充(默認為空格)至指定長度的新字符串,如果指定的長度小於原字符串的長度則返回原字符串。語法:str.ljust(width, fillchar) -> str 返回一個新的字符串width:指定字符串的輸出長度;
fillchar:將要填充的單字符,默認為空格;
str = "python"print(str.ljust(30,"*")) print(str.ljust(30)) print(str.ljust(30),"1")python************************python python 1返回一個原字符串右對齊,並使用fillchar填充(默認為空格)至指定長度的新字符串,如果指定的長度小於原字符串的長度則返回原字符串。str = "python"print(str.rjust(30,"*")) print(str.rjust(30)) print("1",str.rjust(30))************************python python1 python返回指定長度的字符串,使原字符串右對齊,前面用0填充到指定字符串長度。
語法:str.zfill(width) -> str 返回一個字符串width:指定字符串的長度,但不能為空;若指定長度小於字符串長度,則直接輸出原字符串。str = "i love python"print(str.zfill(30)) print(str.zfill(2)) print(str.zfill())00000000000000000i love pythoni love pythonTypeError Traceback (most recent call last)<ipython-input-22-45e4baf7a246> in <module>() 2 print(str.zfill(30)) 3 print(str.zfill(2)) TypeError: zfill() takes exactly 1 argument (0 given)統計字符串裡某個字符出現的次數,可以選擇字符串索引的起始位置和結束位置。str.count("char", start,end) 或 str.count("char") -> int 返回整數str —— 為要統計的字符(可以是單字符,也可以是多字符)。star —— 為索引字符串的起始位置,默認參數為0。end —— 為索引字符串的結束位置,默認參數為字符串長度即len(str)。str = "i love python,i am learning python"print(str.count("i")) print(str.count("i",2)) print(str.count("i",2,5)) print(str.count("am"))在編碼轉換時,通常以 Unicode 作為中間碼,即先將一種類型的字符串解碼(decode)成 Unicode,再從 Unicode 編碼(encode)成另一種類型的字符串。使用字符串對象的 encode()方法可以根據參數 encoding 指定的編碼格式將字符串編碼為二進位數據的字節串。
str.encode(encoding='UTF-8', errors='strict')str 表示字符串對象:參數 encoding 表示要使用得編碼類型,默認為 UTF-8 ,參數 errors 設置不同錯誤的處理方案,默認為 strict,表示遇到非法字符就會拋出異常。
其他取值包括 ignore(忽略非法字符)、replace(用 ? 替換非法字符)、xmlcharrefreplace (使用 XML 的字符引用)、backslashreplace ,以及通過 codecs.register_error() 註冊的任何值。使用 encode()方法對中文字符串進行編碼示例:
u = "中文"str1 = u.encode("gb2312")print(str1)str2 = u.encode("gbk")print(str2)str3 = u.encode("utf-8")print(str3)與 encode() 方法操作相反,使用 decode()方法可以解碼字符串。即根據參數 encoding 指定的編碼格式將二進位數據的字節串解碼為字符串。str.decode(encoding='UTF-8', errors='strict')
str 表示被 decode()解碼的字節串,該方法的參數與 encode()方法的參數用法相同,最後返回解碼後的字符串。u = "中文"str1 = u.encode("gb2312")u1 = str1.decode("gb2312")print(u1) u2 = str1.decode("utf-8") """報錯如下:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 0: invalid continuation byte"""
encode()和decode()方法的參數編碼格式必須一致,否則將拋出上面代碼所字符串在python部的表示是unicode編碼。所以在做編碼轉換時,需要先將其他編碼的字符串解碼(decode)成unicode,再從unicode編碼(encode)成另一種編碼。將其他編碼的字符串轉換成unicode編碼,如string1.decode('utf-8'),表示將utf-8編碼的字符串string1轉換成unicode編碼。將unicode編碼轉換成其他編碼的字符串,如string2.encode('utf-8'),表示將unicode編碼的字符串string2轉換成utf-8編碼。如果一個字符串已經是unicode了,再進行解碼則將出錯,因此通常要對其編碼方式是否為unicode進行判斷:
isinstance(string3, unicode) #用來判斷string3是否為unicode編碼
用非unicode編碼形式的string3來encode也會報錯;import sysprint sys.getdefaultencoding()
string4="你好" if isinstance(string4, unicode): print s.encode('gb2312') else: print s.decode('utf-8').encode('gb2312')面試中問到的python 字符串轉換為int類型的兩種方法;a = "100"
a = int(a)print(a)print(type(a))
print(type(eval(a)))
import string str='555'num=string.atoi(str)最後:
歡迎關注「Python新手快速入門」
每天5分鐘,學習一個Python小Tip! 助力你成為更優秀的Python學習者~