Python 字串處理常用函式

2021-08-21 20:32:39 字數 1683 閱讀 1495

python處理字串有很多常用函式

1. 使用成員操作符in

str = 'hello, world!\n'

sstr = '\n'

result = sstr in str

print(result) # true

2. 使用字串的find()、index()火count()方法

str = 'hello, world!\n'

sstr = '\n'

result = str.find(sstr) >= 0

print(result) # true

result = str.count(sstr) > 0

print(result) # true

result = str.index(sstr) >= 0

print(result) # true

使用split()

str = 'hello, world!\n'

str1, str2 = str.split(',')

print(str1) # hello

print(str2) # world!

sstr = str.split(',')

print(sstr) # ['hello', ' world!\n']

如果用乙個物件來作為splt()的返回值,則是乙個包含這兩個子字串的list。

1. 可以使用isdigit()函式,但有的時候數字是用逗號','隔開的,我希望判斷隔開後的是不是只有數字

str = '3,5'

result = str.isdigit()

print(result) # false

sstr1,sstr2 = str.split(',')

result = sstr1.isdigit()

print(result) # true

2. 然而有時候字串裡有負數,這樣可以先用strip()函式把'-'去掉,再做判斷

str = '-3,5'

result = str.isdigit()

print(result) # false

sstr1,sstr2 = str.split(',')

result = sstr1.isdigit()

print(result) # false

result = sstr1.strip('-').isdigit()

print(result) # true

可以用int()轉換成整型,用float()轉換成浮點型

str = '3,5.2'

sstr1, sstr2 = str.split(',')

result = int(sstr1)

print(result) # 3

result = float(sstr2)

print(result) # 5.2

參考:

Python常用的字串處理函式

1.capitalize 將字串中的第乙個字元大寫,需要注意的是,只有字串的首字元為字母時才能起到大寫作用 2.upper 將字串全部轉成大寫 lower 將字串全部轉成小寫 casefold 同lower 3.title 將每個單詞的首字母變成大寫 istitle 判斷是否title模式 isup...

Python字串處理函式

返回被去除指定字元的字串 預設去除空白字元 刪除首尾字元 str.strip char 刪除首字元 str.lstrip char 刪除尾字元str.strip char 判斷是否匹配首末字元 匹配成功返回true,否則返回false 匹配首字元 str.startswith char start ...

python 字串處理函式

link python常用字串處理函式 在歷史上string類在python中經歷了一段輪迴的歷史。在最開始的時候,python有乙個專門的string的module,要使用string的方法要先import,但後來由於眾多的python使用者的建議,從python2.0開始,string方法改為用...