1 #有用的字符串方法 2 #upper() lower() isupper() islower() 3 print("How are you?") 4 feeling = input() 5 if feeling.lower() == 'great': #用来都转换成小写字母判断 6 print("I feel great too!") 7 else : 8 print("I hope the rest of your day is good.") 9 #验证有用输入的口令 10 while True: 11 print("Enter your age:") 12 age = input() 13 if age.isdecimal(): 14 break 15 print("Please enter a number for your age.") 16 while True: 17 print("Select a new password(letters and numbers only):") 18 password = input() 19 if password.isalnum(): 20 break 21 print("password can only have letters and numbers.") 22 23 #字符串方法startswith() endswith() 24 'Hello word!'.startswith('Hello') 25 'Hello word!'.endswith("swith") 26 27 #字符串方法join和split 28 29 ','.join(['cats','rats','bats']) #对列表的字符串进行拼接 30 ' '.join(['My','name','is','Simon'])#对列表字符串进行拼接 31 #----->'My name is Simon' 32 'ABC'.join(['My','name','is','Simon']) #拼接成新字符串 33 #----->ABCMyABCnameABCisABCSimon 34 'ABCMyABCnameABCisABCSimon'.split('ABC') 35 #----->['My','name','is','Simon'] 36 ####一个最常见的split应用方法就是按照换行符分割多行字符串text.split('\n') 37 38 #rjust ljust center() 使用字符串填充固定长度 39 #打印表格数据 40 def printPicnic(itemsDict,leftWidth,rightWidth): 41 print("PICNIC ITEMS".center(leftWidth+rightWidth,'-')) 42 for k,v in itemsDict.items(): 43 print(k.ljust(leftWidth,'.')+str(v).rjust(rightWidth)) 44 picnicItems = {'sandwiches':4,'apples':12,'cups':4,'cookies':8000} 45 printPicnic(picnicItems,12,5) 46 printPicnic(picnicItems,20,6) 47 48 #strip() rstrip() lstrip() 删除字符串 49 #默认删除空白字符串 也可以自定义删除指定字符串 50 spam = "spamSpamBaconSpamEggsSpamSpamSpam" 51 spam.split('smpa') #字符串的顺序不重要 只要有就删除 52 #---->BaconSpamEggs 字符串两端 删除出现的a'm'p'S 53 54 55 #使用pyperclip模块拷贝粘贴字符串 56 import pyperclip 57 pyperclip.copy("Hello word!") 58 pyperclip.paste() 59 #--->Hello word!