python字串處理常用方法

2021-07-14 20:49:01 字數 2681 閱讀 9173

1》str.find()  str.rfind()  str.index()  str.rindex()  str.count()

>>> s='hello python,hello world!'

>>> s.find('hello')#從左側開始查詢

0>>> s.rfind('hello')#從右側開始查詢

13>>> s.find('wahaha')#查詢失敗,返回-1

-1>>> s.index('hello')#從左側開始查詢

0>>> s.rindex('hello')#從右側開始查詢

13>>> s.index('wahaha')#查詢失敗,丟擲valueerror異常

traceback (most recent call last):

file "", line 1, in

valueerror: substring not found

>>> s.count('hello')#查詢子串的個數

22》str.capitalize()  str.lower()  str.upper() str.swapcase()

>>> s='hello python,hello world!'

>>> s.capitalize()#首字母大寫,其餘的小寫

'hello python,hello world!'

>>> s

'hello python,hello world!'

>>> s.lower()#全部小寫

'hello python,hello world!'

>>> s

'hello python,hello world!'

>>> s.upper()#全部大寫

'hello python,hello world!'

>>> s

'hello python,hello world!'

>>> s.swapcase()#大小寫互換

'hello python,hello world!'

3》str.split()  str.join()

>>> s='python   hello\n\nworld\t\twahaha\r\rabc'

>>> s.split()#預設以 空格或'\n'或'\t'或'\r'為分割符,返回乙個列表,列表中不包含空串

['python', 'hello', 'world', 'wahaha', 'abc']

>>> s='hello   python '

>>> s.split(' ')#指定以空格為分隔符,返回的列表中可能包含空串

['hello', '', '', 'python', '']

>>> l=['abc','def','gh']

>>> '+'.join(l)#以'+'作為連線符

'abc+def+gh'

>>> l

['abc', 'def', 'gh']

>>> ''.join(l)#以空串作為連線符

'abcdefgh'

4》len(str)

>>> s='abc'

>>> len(s)#求字串的長度

3>>> s='連線符'

>>> s

'\xe8\xbf\x9e\xe6\x8e\xa5\xe7\xac\xa6'

>>> len(s)

9>>> s=u'連線符'

>>> s

u'\u8fde\u63a5\u7b26'

>>> len(s)

35》cmp(str1,str2)

>>> help(cmp)

help on built-in function cmp in module __builtin__:

cmp(...)

cmp(x, y) -> integer

return negative if xy.

>>> cmp('abc','ef')# 'abc'<'ef'

-1>>> cmp('abc','abc')# 'abc'>'abc'

1>>> cmp('abc','abc')# 'abc'=='abc'

06》max(str) min(str)

>>> s='abcdefg'

>>> max(s)

'g'>>> min(s)

'a'7》str.startswith()  str.endswith()

>>> s='hello python hello world!'

>>> s.startswith('hell')

true

>>> s.startswith('ok')

false

>>> s.endswith('!')

true

>>> s.endswith('wahaha!')

false

8》str.replace()

>>> s='hello python,hello world!'

>>> s.replace('hello','love')#找到了,就替換

'love python,love world!'

>>> s

'hello python,hello world!'

>>> s.replace('love','love')#找不到,就不換

'hello python,hello world!'

(完)

字串處理常用方法

方法 說明capitalize 將字串首字母大寫,開頭不是字母則不作處理 lower 將字串的字母轉為小寫 upper 將字串的字母轉為大寫 center width fillbyte 返回長度為width的字串,如果長度不足則將整個字串返回,如果長度不夠則用fillbyte兩邊填充 encode ...

Python字串處理方法

python語言對字串物件提供了大量的內建方法用於字串的檢測 替換和排版等操作。使用時需要注意的是,字串物件是不可改變的,所以字串物件所涉及字串 修改 的方法都是返回修改之後的新字串,並不是對原字元做任何修改。s bird,fish,monkey,rabbit s.find fish 結果為5 s....

python 字串常用方法

python 字串的常用方法 1.len str 字串的長度 2.startswith str 檢視字串是否以str子串開頭,是返回true,否則返回false 3.index str 查詢字串中第一次出現的子串str的下標索引,如果沒找到則報錯 4.find str 查詢從第0個字元開始查詢第一次...