Skip to main content
 首页 » 编程设计

python之如何获取字符列表中的所有子字符串(python)

2025年05月04日21zfyouxi

我想遍历一个字符列表

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()”方法,因为它与问题并不特别相关。

请您参考如下方法:

如果您只需要hello 和world 并且您的单词始终以# 分隔,您可以使用join 轻松实现。和 split

>>> temp = ['h', 'e', 'l', 'l', 'o', '#', 'w', 'o', 'r', 'l', 'd'] 
>>> "".join(temp).split('#') 
['hello', 'world'] 

如果您需要打印您需要的完整有效字符串,则更进一步

>>> t = "".join(temp).split('#') 
>>> print(' '.join(t)) 
hello world