python 字符串常見(jiàn)操作

字符串 mystr = 'hello world itcast and itcastcpp',以下是常見(jiàn)的操作

1 ?find

檢測(cè)str是否包含在mystr中,如果是返回開(kāi)始的索引值,否則返回-1

mystr.find(str, start=0, end=len(mystr))

>>>mystr = 'hello world itcast and itcastcpp'

>>>mystr.find('itcast')

12

>>>

>>>mystr.find('itcast',0,10)

-1

>>>

2 index

跟find()方法一樣,只不過(guò)如果str不在 mystr中會(huì)報(bào)一個(gè)異常.

mystr.index(str, start=0, end=len(mystr))

3 count

返回str在star和end之間 在mystr里面出現(xiàn)的次數(shù)

mystr.count(str, start=0, end=len(mystr))

>>>mystr.count('itcast')

2

>>>

4 replace

把mystr中的 str1替換成str2,如果count指定,則替換不超過(guò)count次

mystr.replace(str1, str2, mystr.count(str1))

>>>name = 'hello word ha ha'

>>>name.replace('ha', 'Ha')

'hello word Ha Ha'

>>>name.replace('ha', 'Ha', 1)

'hello word Ha ha'

>>>

5 ?split

以str 為分隔符切片mystr,如果maxsplit有指定值,則僅分隔 maxsplit 個(gè)子字符串

mystr.split(str=" ", 2)

>>>name = 'hello word ha ha'

>>>name.split(' ')

['hello', 'word', 'ha', 'ha']

>>>name.split(' ', 2)

['hello', 'word', 'ha ha']

>>>

6 capitalize

把字符串的第一個(gè)字符大寫(xiě)

mystr.capitalize

>>>mystr.capitalize()

'Hello world itcast and itcastcpp'

>>>

7 title

把字符串的每一個(gè)單詞首字母大寫(xiě)

>>>a = 'how are you'

>>>a.title()

'How Are You'

>>>

8 ?startswith/endswith

檢查字符串是否以obj開(kāi)始/結(jié)束, 是返回True,否則返回False

mystr.startswith(obj)/mystr.endswith(obj)

>>>mystr.startswith('hello')

True

>>>mystr.endswith('hello')

False

9 lower

>>>a = 'HELLO'

>>>a.lower()

'hello'

10 upper

>>>a = 'a b c d'

>>>a.upper()

'A B C D'

11 ljust

返回一個(gè)原字符串左對(duì)齊,并使用空格填充至長(zhǎng)度 width 的新字符串

mystr.ljust(width)

>>> mystr = 'hello'

>>>mystr.ljust(10)

'hello ? ? '

12 rjust

返回一個(gè)原字符串右對(duì)齊,并使用空格填充至長(zhǎng)度 width 的新字符串

mystr.rjust(width) 同11 原理一樣

13 center

返回一個(gè)原字符串居中,并使用空格填充至長(zhǎng)度 width 的新字符串

mystr.center(width)


14 lstrip

刪除 mystr 左邊的空白字符

mystr.lstrip()


15 rstrip

刪除 mystr 字符串末尾的空白字符

16strip

刪除mystr字符串兩端的空白字符

>>>a = '\n\t ?itcast \t\n'

>>>a.strip()

'itcast'

17 rfind

類似find()函數(shù),不過(guò)是從右邊開(kāi)始查找


18 rindex

類似于 index(),不過(guò)是從右邊開(kāi)始


19 partition

把mystr以str分割成三部分,str前,str和str后

mystr.partition(str)


20 rpartition

類似于 partition()函數(shù),不過(guò)是從右邊開(kāi)始.

mystr.rpartition(str)


21 splitlines

按照行分隔,返回一個(gè)包含各行作為元素的列表

mystr.splitlines()


22 isalpha

如果 mystr 所有字符都是字母 則返回 True,否則返回 False

mystr.isalpha()


23? isdigit

如果 mystr 只包含數(shù)字則返回 True 否則返回 False.

mystr.isdigit()


24? isalnum

如果 mystr 所有字符都是字母或數(shù)字則返回 True,否則返回 False

mystr.isalnum()


25? isspace

如果 mystr 中只包含空格,則返回 True,否則返回 False.

mystr.isspace()


26? join

mystr 中每個(gè)字符后面插入str,構(gòu)造出一個(gè)新的字符串

mystr.join(str)


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容