本篇文章將介紹python的字符串操作,更多內(nèi)容請參考:python學(xué)習(xí)指南
一、查看幫助文檔
在學(xué)習(xí)編程語言過程中,不管是python語言還是其它語言時我們都應(yīng)該學(xué)會查看API文檔,查看幫助信息,以便我們進(jìn)行開發(fā)使用。
學(xué)習(xí)python查看文檔有兩種方式:
- 下載官方的API文檔進(jìn)行查閱,官方地址:python官方地址
- 可以在本地搭建好的環(huán)境中,進(jìn)入命令窗口并切換到python環(huán)境,使用dir()和help()方法函數(shù)進(jìn)行查看,比如,我想查看str字符串中有哪些屬性和方法,使用dir(str)命令可以查看,如果想查看具體的某個方法的使用,如index()方法,可以使用help(str.index)的方式查看方法的使用。
二、字符串常見函數(shù)
lower():將字符串全變成小寫;upper():將字符串全變成大寫;原字符串保持不變
#定義一個字符串變量
str1 = "AbCd"
#將str1變成小寫,賦值給str2
str2 = str1.lower()
#將str1變成大寫,賦值給str3
str3 = str1.upper()
find()函數(shù):函數(shù)原型:SttringObject.find(sub, [end]),作用是返回字符串中第一個出現(xiàn)sub的第一個字母的下標(biāo),如果沒有找到sub子串,則返回-1。start和end是可選參數(shù),從start位置下標(biāo)開始,到end位置下標(biāo)結(jié)束,在[start, end]中進(jìn)行查找
str1 = "abcdefghijklmn"
index1 = str1.find("mn", 0, 13)
rfind(),函數(shù)原型:StringObject.rfind(sub, [start, [end]]),返回字符串中最后出現(xiàn)sub的第一個字母的標(biāo)號,如果字符串中沒有sub,則返回-1
>>>str1 = 'abcabcabcabc'
>>>index1 = str1.rfind('ab')
>>>index1
6
index()函數(shù),函數(shù)原型StringObject.index(sub, [start,[end]]),作用跟find函數(shù)一樣
>>>str1 = 'hello world'
>>>index = str1.index('ll')
>>>index
2
>>>index1 = str1.index('xx')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
注意:find()函數(shù)和index()函數(shù)的作用是一樣的,在一個字符串中查找子串的位置下標(biāo)。區(qū)別在于,在沒有找到子串的情況下,find函數(shù)的返回值是-1;而index()函數(shù)就會出現(xiàn)一個ValueError的異常。
count()函數(shù),函數(shù)原型:StringObject.count(sub, [start, [end]]),計算sub在字符串中出現(xiàn)的次數(shù)
#定義一個字符串變量
str1 = "hello,world! hello.python!"
#計算子串'he'在str1字符串中出現(xiàn)的總次數(shù)
countNum = str1.count('he')
replace()函數(shù),函數(shù)原型:StringObject.replace(oldstr, newstr, [, count]),其中count參數(shù)為替換的次數(shù)(不輸入為全部替換)
#定義一個字符串變量
>>>str1 = "xyzxyzxyzxxxx"
#使用replace()函數(shù),將'xyz'替換成'abc'
>>>str2 = str1.replace('xyz', 'abc')
>>>str2
strip()函數(shù),函數(shù)原型:StringObject.strip([char]),把字符串前后有char的字符全部去掉,默認(rèn)去掉空格。lstrip([char]):去掉字符串左邊有char的字符;rstrip([char]):去掉字符串右邊有char的字符。
>>>str1 = ' my name is ... '
>>>str2 = str1.strip()
>>>str2
my name is ...
>>>str3 = '******hello evenyone!*****'
>>>str4 = str3.strip('*')
>>>str4
'hello everyone!'
join()方法,函數(shù)原型:StringObject.join(iterable),其中iterable是可迭代類型如列表。作用是用來在隊(duì)列中添加元素,但需要添加的隊(duì)列元素都必須是字符串。返回值是一個字符串類型。
>>>seq = [1, 2, 3, 4]
>>>sep = '+'
>>>str1 = sep.join(seq)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
split()方法,函數(shù)原型:StringObject.split(sep=None, maxsplit=-1),作用是將字符串分割成序列。sep默認(rèn)情況下是以空格作為分隔符。
>>>dirs = "/usr/bin/env"
>>>dirList = dirs.split("/")
>>>dirList
['', 'user', 'bin', 'env']
三、其它函數(shù)
- capitalize()函數(shù):返回一個首字母大寫的字符串。
- center()函數(shù):S.center(width, [fillchar])->string,返回一個把原字符串移到中間,默認(rèn)把兩邊添加空格的字符串,也可以自己制定填充物
- decode()函數(shù):S.decode([encoding[, errors]])->object,編碼
- encode()函數(shù):S.encode([encoding[, errors]])->object,解碼
- endswith()函數(shù),S.endswith(suffix[,start[, end]])->bool,檢查是否以suffix結(jié)尾,可以指定位置,做循環(huán)的判定條件很有用,免去==!
- isalnum()函數(shù),S.isalnum()->bool,判斷S中是否全為數(shù)字或者字母[并至少有一個字符],是則返回True,沒有字符返回False
- isalpha()函數(shù),S.isalpha()->bool函數(shù),判斷是否全為字母【并且至少有一個字符】
- isdigit()函數(shù),S.isdigit()->bool,判斷是否全為數(shù)字【并且至少有一個數(shù)字】
- islower()函數(shù),S.islower()->bool,判斷字母是否全為小寫(有數(shù)字不影響)【并至少有一個字符】
四、Python字符串運(yùn)算符
| 操作符 | 描述 | 實(shí)例 |
|---|---|---|
| + | 字符串連接 | a = 'hello' + 'python',運(yùn)行結(jié)果:a=‘hellopython’ |
| * | 重復(fù)輸出字符串 | a = '-'*5,運(yùn)行結(jié)果:a = '-----' |
| [] | 通過索引獲取字符串中的字符 | a = 'hello' ,b = a[0],運(yùn)行結(jié)果為:b = 'h' |
| [:] | 截取字符串中一部分字符 | a = 'hello world' ,b = a[1:4],運(yùn)行結(jié)果:b='ell' |
| in | 成員運(yùn)算符,如果字符串中包含給定的字符返回True,不包含返回False | 'h' in a,其中a = ‘hello’,運(yùn)行結(jié)果:True |
| not in | 成員運(yùn)算符,如果字符串中包含給定的字符返回False,不包含返回True | 'h' in a,其中a = ‘hello’,運(yùn)行結(jié)果:False |
| r/R | 原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思來使用,沒有轉(zhuǎn)義特殊或不能打印的字符。 原始字符串除在字符串的第一個引號前加上字母"r"(可以大小寫)以外,與普通字符串有著幾乎完全相同的語法。 | print r'\n',運(yùn)行結(jié)果為:\n |
注意點(diǎn):1、list、str、dict都是可迭代,可用for循環(huán)。
2、計算字符串的長度使用len(str),或者str.len()