本博文包含upper()、lower()、isupper()、islower()、isX、startswith()、endswith()、join()、split()、
upper(),lower():將字符串中所有字母轉化爲大寫和小寫,其他字符不變。isupper(),islower():至少有一個字母,並且所有字母是大寫或小寫就返回Ture。
spam = 'Hello,World!' print (spam.upper()) print (spam.lower()) print ('hello'.upper()) print ('Hello'.isupper()) #返回False print ('hello'.islower()) #返回True
2.isX形式的方法都是返回布爾值
isalpha(),如果字符串只包含字母,並且非空,則返回True
isalnum(),如果字符串只包含字母和數字,並且非空,則返回True
isdecimal(),如果字符串都是數字,並且非空,則返回True
isspace(),如果字符串只包含空格、製表符和換行,並且非空,則返回True
istitle(),如果字符串僅包含以大寫字母開頭、後面都是小寫,則返回True
while True: print ("Please enter your age:") age = input() if age.isdecimal(): break print ('Please enter a number for your age') while True: print ('Please enter your password') password = input() if password.isalnum(): break print ("password can only have letters and unmbers")
3.startswith(),endswith()以傳入參數爲開始和結尾
print ('hello,world'.startswith('hello')) #返回True print ('hello,World'.endswith('world')) #返回False
4.join()將字符串列表連接成字符串。插入到列表每個字符串的中間。
split()將字符串拆成字符串列表。
print ('/'.join(['cat','name'])) #輸出爲:'cat/name' print ('ABC'.join(['cat','name'])) #輸出爲:'catABCname' print ('MyABCnameABCis'.split('ABC')) #輸出爲:['my','name','is'] print ('My name is Tompeter'.split('m')) #輸出爲:['My na','e is To','peter']
5.strip()、lstrip()和rstrip()分別表示刪除字符串兩端、左端、右端的空白字符(空格、製表符和換行)
spam = ' Hello world ' print (spam.strip()) #輸出爲‘Hello world’ print (spam.lstrip()) #輸出爲‘Hello world ’ print (spam.rstrip()) #輸出爲‘ Hello world’ spam_test = 'SpampSmabbbbbampS' print (spam_test.strip('Spam')) #輸出爲‘bbbbb’
strip('Spam')表示刪除左右兩端a、m、p和大寫S,字符串的順序並不重要。等價於strip('pSam')等