簡體   English   中英

如何使用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)

鑒於您打算做什么,也許這不是最實用的方法 - 您可能應該有一個函數來獲取一系列標記作為輸入(可以是列表,也可以是帶有單字母標記的字符串) , 以及有關如何分組和插入字符的說明,然后將其作為字符串返回:

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 個條目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM