python學習筆記(四)字符串及字符串操作
阿新 • • 發佈:2018-01-01
默認 小寫字母 是不是 swap git 查找字符 英文 去掉 title
字符串
字符串可以存任意類型的字符串,比如名字,一句話等等。
字符串還有很多內置方法,對字符串進行操作,常用的方法如下:
1 name1=‘hello world‘ 2 print(name.capitalize())#首寫字母大寫 3 print(name1.capitalize())#首寫字母大寫Hello world 4 print(name1.center(50,‘-‘))#50個-,把name1放中間-------------------hello world-------------------- 5 print(name.endswith(‘u‘))#是否以x結尾 False6 print(name1.endswith(‘d‘))#是否以x結尾 True 7 print(name.expandtabs(30))#補入\t的次數my name is {name},age is{age}. 8 print(name1.find(‘n‘))#查找字符串的索引5(\t代表3個字符) 9 print(name.format(name=‘niuniu‘,age=18))#這個是格式字符串my name is niuniu,age is18. 10 print(name.format_map({‘name‘:‘niuniu‘,‘age‘:19}))#這個也是格式化字符串,後面跟的是一個字典,字典在後面也會寫 11 #my name is niuniu,age is19. 12 print(‘abA123‘.isalnum())#是否包含數字和字母 True 13 print(‘abA‘.isalpha())#是否有英文字母True
1 name = ‘My \t name is {name},age is{age}.‘ 2 print(‘122‘.isdigit())#是否有數字True 3 print(‘aa‘.isidentifier())#是否是一個合法的變量名True4 print(‘aa‘.islower())#是否是小寫字母True 5 print(‘AA‘.isupper())#是否是大寫字母True 6 print(‘Loadrunner Book‘.istitle())#是不是一個標題,判斷首字母是否大寫True 7 print(‘+‘.join([‘hehe‘,‘haha‘,‘ee‘]))#拼接字符串 hehe+haha+ee 8 print(name.lower())#變成小寫my name is {name},age is{age}. 9 print(name.upper())#變成大寫MY NAME IS {NAME},AGE IS{AGE}. 10 print(‘\nmysql \n‘.lstrip())#默認去掉左邊的空格和換行 11 print(‘\nmysql \n‘.rstrip())#默認去掉右邊的空格和換行 12 print(‘\nmysql \n‘.strip())#默認去掉兩邊的空格和換行 13 p=str.maketrans(‘abcdefg‘,‘1234567‘)#前面的字符串和後面的字符串做映射 14 print(‘cc ae gg‘.translate(p))#輸出按照上面maketrans做映射後的字符串33 15 77
1 new_p=str.maketrans(‘1234567‘,‘abcdefg‘) 2 print(‘cc ae gg‘.translate(new_p)) 3 print(‘mysql is db.‘.replace(‘mysql‘,‘oracle‘,1))#替換字符串oracle is db. 4 print(‘mysql is db.mysql is db.mysql is db.‘.replace(‘mysql‘,‘oracle‘,2))#替換字符串oracle is db.oracle is db.mysql is db. 5 print(‘mysql is is db‘.rfind(‘is‘))#返回最右邊字符的下標 9 6 print(‘1+2+3+4‘.split(‘+‘))#切割字符串,返回一個list [‘1‘, ‘2‘, ‘3‘, ‘4‘] 7 print(‘1+2+3\n1+2+3+4‘.splitlines())#按照換行符分割[‘1+2+3‘, ‘1+2+3+4‘] 8 print(‘Abcdef‘.swapcase())#大小寫反轉aBCDEF
python學習筆記(四)字符串及字符串操作