如何用字符串替换单词列表并在python中保留格式?

2024-04-25 19:44:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含文件行的列表。你知道吗

list1[0]="this is the first line"
list2[1]="this is the second line"

我还有一根绳子。你知道吗

example="TTTTTTTaaaaaaaaaabcccddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffff"

我想用字符串替换列表[0](示例)。但是我想保持这个词的长度。例如,新的list1[0]应该是"TTTT TT TTa aaaaa aaaa"。我能想到的唯一解决方案是将字符串示例转换为一个列表,并使用for循环将字符串列表中的字母逐字读取到原始列表中。你知道吗

for line in open(input, 'r'):
        list1[i] = listString[i]
        i=i+1

但是,这与我的理解不符,因为Python字符串是不可变的?初学者解决这个问题的好方法是什么?你知道吗


Tags: 文件the字符串示例列表forisexample
1条回答
网友
1楼 · 发布于 2024-04-25 19:44:13

我可能会这样做:

orig = "this is the first line"
repl = "TTTTTTTaaaaaaaaaabcccddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffff"

def replace(orig, repl):
    r = iter(repl)
    result = ''.join([' ' if ch.isspace() else next(r) for ch in orig])
    return result

如果repl可能比orig短,请考虑r = itertools.cycle(repl)

它的工作原理是从替换字符串中创建一个迭代器,然后在原始字符串上迭代,保留空格,但使用替换字符串中的下一个字符而不是任何非空格字符。你知道吗

您可以采取的另一种方法是在一次通过orig的过程中注意到空间的索引,然后在那些通过repl的索引处插入它们,并返回结果的一部分

def replace(orig, repl):
    spaces = [idx for idx,ch in enumerate(orig) if ch.isspace()]
    repl = list(repl)
    for idx in spaces:
        repl.insert(idx, " ")
        # add a space before that index
    return ''.join(repl[:len(orig)])

然而,我无法想象第二种方法会更快,肯定是内存效率更低,而且我不觉得它更容易阅读(事实上我发现它更难阅读!)如果replorig短,它也没有简单的解决方法(我猜你可以做repl *= 2,但这比sin更难看,仍然不能保证它能工作)

相关问题 更多 >