如何在for循环中拆分字符串

时间:2015-10-23 15:51:10

标签: python string for-loop split

我有一个字符串列表,如下所示:

"Your friend Nicky thought you'd like this product from WorldStores",
"Your friend Denise Holder thought you'd like this product from BedroomFurnitureWorld",

等等

我想把列表变成句子的最后一个单词。 到目前为止我的尝试是:

test = []
for i in sites:
    a = i.split('from ')
    a = a[1]
    test.append(a)

当我跑步时,我得到了

a = a[1]

IndexError: list index out of range

而当我为每个字符串单独执行时,它可以工作

In: a = i.split('from ')
Out: ["Your friend Jack thought you'd like this product ", 'BedroomFurnitureWorld']

In: a[1]
Out: 'BedroomFurnitureWorld'

如何在for循环中执行此操作?

3 个答案:

答案 0 :(得分:1)

sites中的一个句子缺少分隔符:

>>> sentence = 'I am missing the separator!'
>>> a = sentence.split('from ')
>>> a = a[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

使用if-statment修复数据或保护逻辑:

test = []
for i in sites:
    a = i.split('from ')
    if len(a) > 1:
        a = a[1]
        test.append(a)

我的猜测是你的sites之一是一个空字符串。

答案 1 :(得分:0)

如果您只需要句子中的最后一个单词,则以下内容应该有效。

test = []
    for i in sites:
        a = i.split()
        if a:
            test.append(a[-1])

答案 2 :(得分:0)

很可能是因为sites中的所有行都不符合您预期的.*from \S+$格式。

这(下面)不仅会起作用,还会报告有问题的行 -

sites = [
    "Your friend Nicky, from DC, thought you'd like this product from WorldStores",
    "Your friend Denise Holder thought you'd like this product from Bedroom Furniture World",
    "Your friend Eric thought you'd like this product from",
    ]

test = []
for i in sites:
    a = i.rsplit("from ", 1)
    try:
        test.append(a[1])
    except IndexError:
        print "This input line is not kosher - \"" + i + "\""

使用最多1分割的rsplit()更安全。