我想在python中使用字符串的排列:
string= asis:abc
permutations = ["".join(x) for x in permutations(string,len(string))]
print permutations
但是我需要在这个例子之后开始:即我想获得这样的东西:
asis:abc, asis:acb, asis:bca, asis:bac, ...
我该怎么办?
答案 0 :(得分:3)
这应该这样做:
from itertools import permutations
s = 'asis:abc'
delimiter = ':'
pre, post = s.split(delimiter)
for p in permutations(post):
print '{}{}{}'.format(pre, delimiter, ''.join(p))
输出:
asis:abc
asis:acb
asis:bac
asis:bca
asis:cab
asis:cba
或者您可以通过将for循环替换为列表解析来将值存储在列表中:
perms = ['{}{}{}'.format(pre, delimiter, ''.join(p)) for p in permutations(post)]