Python求包含數字或字母最長的字符串及長度
阿新 • • 發佈:2017-10-18
一個 sdf 最終 字母 遇到 ear amp sdfs pen
一、需求:求包含數字或字母最長的字符串及長度
org = ‘ss121*2222&sdfs2!aaabb‘ result = [] #保存最終要輸出的字符串 result_temp = [] #保存當前最長的字符串 max_len = 0 #保存最長字符串的長度 for c in org + ‘ ‘: #多加一次循環,為了最後多執行一次else; 否則若字符串末尾滿足條件,將不會保存到result中 if c.isalnum(): #若c為數字或字母,則加入result_temp中 result_temp.append(c) else: #直到遇到一個非數字和字母時,判斷當前result_temp的長度len_temp = len(result_temp) if len_temp > max_len: #若大於當前最大長度,則清空result,把該字符串加入reseult中 max_len = len_temp result.clear() result.append(‘‘.join(result_temp)) elif len_temp == max_len: #若等於當前最大長度,說明存在兩個長度一樣的字符串,直接把該字符串加入result中 result.append(‘‘.join(result_temp)) result_temp = [] #遇到非數字和字母時,清空result_temp,繼續下一次遍歷 if len(result) == 0: print(‘沒有符合標準的字符串‘) else: print(‘符合要求的最長字符串的長度為: ‘, max_len) print(‘符合要求的最長字符串有: ‘, result)
Python求包含數字或字母最長的字符串及長度