如何使用 python 在字符串中间插入一个或多个字符?

How to insert one or more character in the middle of a string using python?

我想列出 n 元素组的所有可能的关联操作。比如当n=3时,我要打印:

a*(a*a)  =  (a*a)*a
a*(a*b)  =  (a*a)*b
a*(a*c)  =  (a*a)*c
... 24 more lines

现在,我最好的尝试是生成这些代码 python3。

import itertools as it

def permutation_func(str_, rep):
  chars = list(str_)
  results = []
  for tuple_ in it.product(chars, repeat = rep):
    i = ''.join(tuple_)
    results.append(i)
  return results
 
my_list = permutation_func('abc', 3)

for i in my_list:
    print(i, " = ", i)

但是,我得到的输出是:

aaa  =  aaa
aab  =  aab
aac  =  aac
... and 24 more lines

我认为我走在正确的轨道上。但我无法弄清楚如何将 aaa = aaa 转换为 a*(a*a) = (a*a)*a 基本上我需要在文本中多次插入 * 符号和括号。

我尝试使用谷歌搜索,发现我需要正则表达式来执行此操作。但是,我从未使用过正则表达式。所以我正在寻找一种不使用正则表达式的替代方法。我什至不知道如果没有正则表达式是否可行。如果不是,请告诉我。

不幸的是,Python 中的字符串不是可变对象 - 因此您只能在某个位置插入一个字符。 (而且正则表达式也无济于事——它们有一种奇特的机制来替换一些文本,虽然可以通过调用 re.sub 来完成你想要的插入,但找出正确的正则表达式和回调函数来这样做不值得)

另一方面,Python的list是可以任意改变的序列。幸运的是,有一种简单的机制可以将字符串转换为列表并返回。有了列表后,您可以使用 .insert 方法或切片赋值来插入您的值:

a = "aaa"
b = list(a)
b.insert(1, "*")
b.insert(2, "(")
b.insert(4, "*")
b.insert(6,")")
c = "".join(b)

考虑到你打算做什么,也许这不是最实用的方法 - 你可能应该有一个函数来获取一系列标记作为输入(可以是一个列表,或者一个带有一个字母标记),以及如何分组和插入字符的说明,然后 return 它作为一个字符串:

def group_tokens(tokens, start, end, join="*"):
    output = ""
    for index, token in enumerate(tokens):
        if index != 0:
            output += join
        if index == start:
            output += "("
        elif index == end:
            output += ")"
        output += token
    if end >= len(tokens):
        output += ")"
    return output

根据评论,以下应该有效

for c1, c2, c3 in itertools.product('abc', repeat=3):
    print(f'({c1}*{c2})*{c3} = {c1}*({c2}*{c3})')

它打印:

(a*a)*a = a*(a*a)
(a*a)*b = a*(a*b)
(a*a)*c = a*(a*c)
... 24 more

如果将字符串替换为 abcd,将生成 64 个条目。