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

时间:2015-03-27 18:07:21

标签: python string list python-3.x iteration

我想迭代一个字符列表

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']

等。如何只打印完整的有效字符串?

编辑:我应该更具体地说明什么是&#34;有效&#34;串。只要字符串中的所有字符都是字母或数字,字符串就是有效的。我没有包含&#34; isnumerical()&#34;我的检查条件中的方法,因为它与问题并不特别相关。

5 个答案:

答案 0 :(得分:6)

如果您只想要helloworld并且您的字词始终#已分开,则可以使用joinsplit轻松完成此操作

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

如果您需要print所需的完整有效字符串

,还需要更多
>>> t = "".join(temp).split('#')
>>> print(' '.join(t))
hello world

答案 1 :(得分:1)

你可以这样做:

''.join(temp).split('#')

答案 2 :(得分:1)

List使用方法index返回元素的位置。您可以使用切片来连接字符。

In [10]: temp = ['h', 'e', 'l', 'l', 'o', '#', 'w', 'o', 'r', 'l', 'd']
In [11]: pos = temp.index('#')
In [14]: ''.join(temp[:pos])
Out[14]: 'hello'
In [17]: ''.join(temp[pos+1:])
Out[17]: 'world'

答案 3 :(得分:0)

如果你只想要alphas,只需使用isalpha()替换#和任何其他带空格的非字母,然后拆分你想要一个单词列表:

print("".join(x  if x.isalpha() else " " for x in temp).split())

如果您想在单个字符串中使用两个单词,请用空格替换#并使用条件表达式连接:

print("".join(x if x.isalpha() else " " for x in temp))
hello world

要使用像您自己的代码一样的循环来迭代项目并添加到输出字符串是isalpha else为输出添加空格:

out = ""
for s in temp:
    if s.isalpha():
        out += s
    else:
        out += " "

使用循环获取单词列表:

words  = []
out = ""
for s in temp:
    if s.isalpha():
        out += s
    else:
        words.append(out)
        out = ""

答案 4 :(得分:0)

基于itertools的备用解决方案:

>>> temp = ['h', 'e', 'l', 'l', 'o', '#', 'w', 'o', 'r', 'l', 'd']
>>> import itertools
>>> ["".join(str)
     for isstr, str in itertools.groupby(temp, lambda c: c != '#') 
     if isstr]
['hello', 'world']

itertools.groupby用于......以及分组连续项目,具体取决于它们是否不等于#。理解列表将丢弃仅包含#join#子列表的子列表。

唯一的好处就是这样,你不必构建全字符串只是为了以后拆分它。如果字符串真的很长,可能只相关。