I'm kind of new in python and I have problem to write a script which take four element (ex str, Replacefrom, replaceto and n) find the characters and replace the nth occurrence.
Example:
>>> replaeceit("Mississippi", "s", "l", 2)
'Mislissippi'
>>> replae开发者_开发技巧ceit("Mississippi", "s", "l", 0)
'Mississippi'
the n is 2 so the code change the second s to l .. and when the n=0 then it dosen't do nything
honestly I don't know how to implement n to the equation this is my code so far without n
def replaceit(str,replacefrom,replaceto):
new=""
for letter in str:
if letter== replacefrom:
new=new+replaceto
else:
new=new+letter
return new
Okay, maybe now I understood what you are looking for:
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
Output:
In [84]: replaceit("Mississipi", "s", "l", 2)
Out[84]: 'Mislissipi'
Of course you can check that the arguments no2 and no3 are strings with len() of 1.
This is second first attempt at understanding your question:
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
This matches your examples:
>>> replaceit("Mississippi", "s", "l", 2)
'Mislissippi'
>>> replaceit("Mississippi", "s", "l", 0)
'Mississippi'
If this is not what you want, please explain better.
You can also achieve the same with regular expressions:
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)
Everyone always loves a generator expression.
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)
精彩评论