我是python中的新手,我有一个问题就是编写一个脚本,它接受四个元素(ex str,Replacefrom,replaceto和n)找到字符并替换第n个匹配项。
示例:
>>> replaeceit("Mississippi", "s", "l", 2)
'Mislissippi'
>>> replaeceit("Mississippi", "s", "l", 0)
'Mississippi'
n是2,所以代码将第二个s改为l ..当n = 0时,它就不会做任何事情
老实说,我不知道如何在方程式中实现n这是我的代码到目前为止没有n
def replaceit(str,replacefrom,replaceto):
new=""
for letter in str:
if letter== replacefrom:
new=new+replaceto
else:
new=new+letter
return new
答案 0 :(得分:3)
好吧,也许现在我明白了你在找什么:
def replaceit(st, remove, put, pos):
outs = ""
count = 0
for letter in st:
if letter == remove:
count += 1
if count == pos:
outs += put
else:
outs += letter
else:
outs += letter
return outs
输出:
In [84]: replaceit("Mississipi", "s", "l", 2)
Out[84]: 'Mislissipi'
当然你可以检查参数no2和no3是len()为1的字符串。
答案 1 :(得分:1)
这是理解你的问题的第二次尝试:
def replaceit(s, replacefrom, replaceto, n):
new_s, count = '', 0
for letter in s:
if letter == replacefrom:
count += 1
if count == n:
new_s += replaceto
continue
new_s += letter
return new_s
这符合您的示例:
>>> replaceit("Mississippi", "s", "l", 2)
'Mislissippi'
>>> replaceit("Mississippi", "s", "l", 0)
'Mississippi'
如果这不是您想要的,请更好地解释。
您也可以使用正则表达式实现相同的目标:
def replaceit(s, replacefrom, replaceto, n):
import re
if n <= 0:
return s
return re.sub('(.*?%s)%s' % (('%s.*?' % replacefrom) * (n-1), replacefrom), r'\1%s' % replaceto, s)
答案 2 :(得分:0)
每个人都喜欢发电机表达。
from itertools import count
def replaceit(str, replacefrom, replaceto, n):
c = count(1)
return ''.join(replacefrom if l == replaceto and c.next() == n else l for l in str)