python3 字符串操作
阿新 • • 發佈:2017-12-20
字符串 python3 string split strip
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")) #打印顯示 0 #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
python3 字符串操作