天天看點

python3字元串操作_python3 字元串操作

name = "My \tname is {name} and my age is {year} old"#大寫

print(name.capitalize()) # 首字母大寫

列印顯示

My name is {name} and my age is {year} old

#統計

print(name.count("a")) # 統計 a 的個數

#列印顯示

5

#中間補齊

print(name.center(50,"#"))

#列印顯示

###My name is {name} and my age is {year} old###

#判斷字元串以什麼結尾,正确為true ,錯誤為false

print(name.endswith("ex"))

#列印顯示

False

#tab 健補全

print(name.expandtabs(tabsize=10)) #10 表示10個字元

#查找字元索引

print(name.find("M"))

#列印顯示

#format 格式化

print(name.format(name='bob',year=33))

print(name.format_map({'name':'jerrt','year':27}))

#列印顯示

My name is bob and my age is 33 old

My name is jerrt and my age is 27 old

#如果 string 至少有一個字元并且所有字元都是字母或數字則傳回 True,否則傳回 False

print('a31'.isalnum())

#列印顯示

True

#判斷是否為純英文字元

print('abA'.isalpha())

print('abA1'.isalpha())

#列印顯示

True

False

#判斷是否為10進制

print('1A'.isdecimal())

print('113'.isdecimal())

#列印顯示

False

True

#檢測字元串是否隻由數字組成

print('111'.isdigit())

print('1AA'.isdigit())

#列印顯示

True

False

#判斷是否為合法的辨別符

print('1A'.isidentifier())

print('_1A'.isidentifier())

False

True

#方法檢測字元串是否隻由數字組成。這種方法是隻針對unicode對象

print('a AA'.isnumeric())

print('11'.isnumeric())

#列印顯示

False

True

#檢測字元串是否隻由空格組成

print('ssA'.isspace())

print('ssA'.isspace())

print(' '.isspace())

#列印顯示

False

False

True

#判斷字元串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫則傳回 True,否則傳回 False.

print('My name is '.istitle())

print('My'.istitle())

#列印顯示

False

True

#檢測字元串中所有的字母是否都為大寫

print('MY NAME'.isupper())

print('My Name is'.isupper())

#列印顯示

True

False

#join 方法 用于将序列中的元素以指定的字元連接配接生成一個新的字元串

print("+".join(['a1','b2','c3']))

#列印顯示

a1+b2+c3

#ljust 傳回一個原字元串左對齊,并使用空格填充至指定長度的新字元串。如果指定的長度小于原字元串的長度則傳回原字元串。

name = name = "My \tname is {name} and my age is {year} old"

print(name.ljust(50,"*"))

#列印顯示

My name is {name} and my age is {year} old******

#rjust 傳回一個原字元串右對齊,并使用空格填充至長度 width 的新字元串。如果指定的長度小于字元串的長度則傳回原字元串。

print(name.rjust(50,"*"))

******My name is {name} and my age is {year} old

#lower 大寫變小寫

print('BAG'.lower())

#列印顯示

bag

#upper 小寫變成大寫

print('bob'.upper())

#列印顯示

BOB

#用于截掉字元串左邊的空格或指定字元

print('\nAlex'.lstrip('n')) #從左邊去空格

#列印顯示

Alex

print('Alex\n'.rstrip('\n')) #從右邊去空格

#列印顯示

Alex

#strip 用于移除字元串頭尾指定的字元(預設為空格)

print(' Alex\n'.strip()) #去空格

#列印顯示

Alex

#replace() 方法把字元串中的 old(舊字元串) 替換成 new(新字元串),如果指定第三個參數max,則替換不超過 max

print('Bobbb'.replace('b','B',2))

print('bob'.replace('b','B'))

#列印顯示

BoBBb

BoB

#split 通過指定分隔符對字元串進行切片,如果參數num 有指定值,則僅分隔 num 個子字元串

print('ljack lex lbob ltim '.split('l'))

print('1+2+3+4'.split('+')) #按照+ 區分

#列印顯示

['', 'jack ', 'ex ', 'bob ', 'tim ']

['1', '2', '3', '4']

#title 标題

print('hi world'.title())

#列印顯示

Hi World

#zfill 自動補位 方法傳回指定長度的字元串,原字元串右對齊,前面填充0

print('lex li'.zfill(10))

#列印顯示

0000lex li