Python字符串解析方法彙總

Python字符串方法解析
python

1.capitalize 將首字母大寫,其他的變成小寫git

print('text'.capitalize())
print('tExt'.capitalize())
結果:
Text
Text

 

2.center  將字符串居中  ljust(從左到右填充),rjust(從右到左填充)
api

a='test'
print(a.center(20,'_'))
print(a.rjust(20,'_'))
結果:
________test________
________________test

  

3.count  彙總次數spa

print('alex is alph'.count('a'))    #a在a1 中出現的次數
print('alex is alph'.count('a',0,4))    #a在a1中從第0個位置到第4個位置出現的次數
結果:
2
1

  

4.endswith/startswith   判斷是否以指定的字符結尾/開始
code

str = 'I love chinese'
print(str.endswith('ph'))
print(str.endswith('se'))
print(str.startswith('i'))
結果:
False
True
False

  

5.expandtabs 將tab鍵轉換爲空格默
orm

test = "Our\ttime"
print(test.expandtabs())        #認爲8個空格
print(test.expandtabs(1))       #指定參數爲1個空格
結果:
Our     time
Our time

  

6.format 字符串的格式化
對象

a1='hello {0} ,age: {1}'
print(a1.format('alex',33))
結果:
hello alex,age:33

  

7.isalnum(判斷是不是數字和字符)、isalpha(判斷是不是字符)、isdigit(判斷是不是數字)blog

print('text'.isalpha())    #判斷是不是字符
print('text'.isdigit())    #判斷是不是數字
print('123'.isdigit())     
print('Text123'.isalnum())  #判斷是不是數字和字符
結果:
True
False
True
True

  

8.islower/isupper   判斷是不是小寫/大寫
ip

print('Text'.isupper())
print('TEXT'.isupper())
print('Text'.islower())
print('text'.islower())
結果:
False
True
False
True

  

9.join   鏈接字符(鏈接的是可迭代對象)
字符串

li = ['alex','li']
print("".join(li))
print("-".join(li))
結果:
alexli
alex-li

  

10.lstrip,rstrip,strip  去除空格 

a = ' alex '
print(a.rstrip())    #去除右邊空格
print(a.lstrip())    #去除左邊空格
print(a.strip())     #去除兩邊空格
結果:
 alex
alex 
alex

  

11.replace   替換指定的字符或字符串

a = 'alexaaa'
print(a.replace('a','b'))     #a替換爲b,默認替換全部
print(a.replace('a','b',2))   #從左到右將替換2次a 
結果:
blexbbb
blexbaa

  

12.split  分割字符串,並將分割後的結果返回爲一個list

print('I am Chinese man'.split('a'))
結果 :
['I ', 'm Chinese m', 'n']
相關文章
相關標籤/搜索