Python 3.3:拆分字符串并创建所有组合

时间:2014-04-07 11:40:01

标签: python regex list python-3.x

我正在使用Python 3.3。我有这个字符串:

"Att education is secondary,primary,unknown"

现在我需要拆分最后三个单词(可能有更多或只有一个)并创建所有可能的组合并将其保存到列表中。像这里:

"Att education is secondary"
"Att education is primary"
"Att education is unknown"

最简单的方法是什么?

3 个答案:

答案 0 :(得分:3)

data = "Att education is secondary,primary,unknown"
first, _, last = data.rpartition(" ")
for item in last.split(","):
    print("{} {}".format(first, item))

<强>输出

Att education is secondary
Att education is primary
Att education is unknown

如果你想要列表中的字符串,那么在列表推导中使用相同的内容,比如

["{} {}".format(first, item) for item in last.split(",")]

注意:如果逗号分隔值中间或值本身中有空格,则可能无效。

答案 1 :(得分:3)

a = "Att education is secondary,primary,unknown"
last = a.rsplit(maxsplit=1)[-1]
chopped = a[:-len(last)]

for x in last.split(','):
    print('{}{}'.format(chopped, x))

如果你可以保证你的单词用一个空格分隔,那么它也会起作用(更优雅):

chopped, last = "Att education is secondary,primary,unknown".rsplit(maxsplit=1)
for x in last.split(','):
    print('{} {}'.format(chopped, x))

只要最后一句话就能正常工作。分隔符不包含空格。

输出:

Att education is secondary
Att education is primary
Att education is unknown

答案 2 :(得分:2)

s="Att education is secondary,primary,unknown".split()

w=s[1]
l=s[-1].split(',')

for adj in l:
    print(' '.join([s[0],w,s[2],adj]))