如何在 Python 中为排列添加前缀和后缀?

时间:2020-12-21 18:40:41

标签: python tuples permutation

我正在尝试制作一个以 X 为前缀、以 Y 为后缀的排列列表。 以下是我尝试过的一些示例。


perm = permutations ([1,2,3], 3)

for i in list(perm):
    print ("Adam" + (i) + "Bob")

这会带回错误“TypeError: can only concatenate str (not "tuple") to str”


perm = permutations ([1,2,3], 3)

for i in list(perm):
    list (i)
    
def blink():
    print (("X" + (i) + "Y"))

blink()

这会带回错误“TypeError: can only concatenate str (not "tuple") to str”

理想情况下,最终结果将打印

X(1, 2, 3)Y
X(1, 3, 2)Y
X(2, 1, 3)Y
X(2, 3, 1)Y
X(3, 1, 2)Y
X(3, 2, 1)Y

1 个答案:

答案 0 :(得分:0)

每个元素都是一个元组,所以先用str把它转换成字符串:

for i in perm:
    print("Adam" + str(i) + "Bob")

或者,只使用 f 字符串:

for i in perm:
    print(f"Adam{i}Bob")