一、求包含數字或字母最長的字符串及長度
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)
二、求包含數字和字母最長的字符串及長度
org = 'ss121*2222&sdfs2!aaabb' result = [] #保存最終要輸出的字符串 result_temp = [] #保存當前最長的字符串 max_len = 0 #保存最長字符串的長度 for c in org+' ': if c.isalnum(): #若字符是字母或者數字,則保存 result_temp.append(c) else: len_temp = len(result_temp) result_temp_str = ''.join(result_temp) if not result_temp_str.isalpha() and not result_temp_str.isdigit(): #若字符串不全為字母或全為數字,則該字符串一定同時包含字母和數字 if len_temp > max_len: max_len = len_temp result.clear() result.append(result_temp_str) elif len_temp == max_len: result.append(result_temp_str) result_temp = [] if len(result): print('最長的字符串為: ', result, ' 長度為: ', max_len) else: print('沒有滿足要求的字符串')
三、另一種思路
1、現將字符串中所有非數字和字母的特殊字符替換為統一的一個特殊字符
2、將字符串進行分割
3、用兩個list,分別保存包含數字和字母的字符串及其長度
4、遍歷保存長度的list,提取值最大的下標,從而從保存字符串的list中取出對應的字符串
import string str1 = 'ss121*2222&sdfs2!aaabb' t = string.punctuation #獲取所有的特殊字符 for c in str1: #替換特殊字符 if c in t: str1 = str1.replace(c, '.') list1 = str1.split('.') #分割字符串 list2 = [] #保存所有包含字母和數字的字符串 len_list2 = [] #保存字符串對應的長度 for str2 in list1: if not str2.isdigit() and not str2.isalpha() and len(str2.strip()) > 1: list2.append(str2) len_list2.append(len(str2.strip())) max_len = max(len_list2) max_len_count = len_list2.count(max_len) result = [] if max_len_count > 1: #有多個長度相同的字符串 for length in range(len(len_list2)): if len_list2[length] == max_len: result.append(list2[length]) elif max_len_count == 1: result = list2[len_list2.index(max_len)] else: print('沒有滿足要求的字符串') exit(0) print('最長的字符串為: ', result, ' 長度為: ', max_len)