根据lis替换字符串中的子字符串

2024-10-03 09:07:20 发布

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

根据教程要点:

The method replace() returns a copy of the string in which the occurrences of old have been replaced with new. https://www.tutorialspoint.com/python/string_replace.htm

因此可以使用:

>>> text = 'fhihihi'
>>> text.replace('hi', 'o')
'fooo'

有了这个想法,给定一个[1,2,3]列表和一个'fhihihi'字符串,根据它的位置,可以用某种方法来替换hi为1、2或3吗?例如,该理论解将产生:

'f123'

任何解决方案都必须是无限扩展的。你知道吗


Tags: ofthetextinwhichstring教程hi
3条回答

可以使用初始字符串创建format string

>>> text = 'fhihihi'
>>> replacement = [1,2,3]
>>> text.replace('hi', '{}').format(*replacement)
'f123'

使用^{}

import re

counter = 0

def replacer(match):
    global counter
    counter += 1
    return str(counter)

re.sub(r'hi', replacer, text)

这将比使用str.replace的任何替代方法都要快得多

一种含有re.sub的溶液:

text = 'fhihihi'
lst = [1,2,3]

import re
print(re.sub(r'hi', lambda g, l=iter(lst): str(next(l)), text))

印刷品:

f123

相关问题 更多 >