我想遍历一个字符列表
temp = ['h', 'e', 'l', 'l', 'o', '#', 'w', 'o', 'r', 'l', 'd']
这样我就可以获得两个字符串,"hello"
并且"world"
我目前的方法是:
#temp is the name of the list
#temp2 is the starting index of the first alphabetical character found
for j in range(len(temp)):
if temp[j].isalpha() and temp[j-1] != '#':
temp2 = j
while (temp[temp2].isalpha() and temp2 < len(temp)-1:
temp2 += 1
print(temp[j:temp2+1])
j = temp2
问题是这打印出来
['h', 'e', 'l', 'l', 'o']
['e', 'l', 'l', 'o']
['l', 'l', 'o']
['l', 'o']
['o']
等等。如何只打印完整的有效字符串?
编辑:我应该更具体地说明什么构成“有效”字符串。字符串有效,只要其中的所有字符都是字母或数字即可。我没有在检查条件中包括“ isnumerical()”方法,因为它与问题不是特别相关。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句