替换字符串Python中的特定实例

2024-05-17 16:14:55 发布

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

我知道下面是如何用另一个字符串替换字符串I

line.replace(x, y)

但我只想替换行中x的第二个实例。你是怎么做到的? 谢谢

编辑 我本以为我可以问这个问题而不必详细说明,但不幸的是,没有一个答案在我的情况下起作用。我正在写一个文本文件,并使用下面的代码来更改该文件。你知道吗

with fileinput.FileInput("Player Stats.txt", inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(chosenTeam, teamName), end='')

但是如果chosenTeam出现多次,那么所有的chosenTeam都会被替换。 在这种情况下,如何仅替换第n个实例。你知道吗


Tags: 文件实例字符串答案代码编辑withline
3条回答

这其实有点棘手。首先使用str.find在第一次出现之后获取索引。然后切片并应用replace(计数为1,以便只替换一个引用)。你知道吗

>>> x = 'na'
>>> y = 'banana'
>>> pos = y.find(x) + 1
>>> y[:pos] + y[pos:].replace(x, 'other', 1)
'banaother'

另外,这是一种替换字符串中出现的“n”的方法

def nth_replace(str,search,repl,index):
    split = str.split(search,index+1)
    if len(split)<=index+1:
        return str
    return search.join(split[:-1])+repl+split[-1]

示例:

nth_replace("Played a piano a a house", "a", "in", 1) # gives "Played a piano in a house"

你可以试试这个:

import itertools
line = "hello, hi hello how are you hello"
x = "hello"
y = "something"
new_data = line.split(x)
new_data = ''.join(itertools.chain.from_iterable([(x, a) if i != 2 else (y, a) for i, a in enumerate(new_data)]))

相关问题 更多 >