Reputation: 1305
I am writing a program like unix tr, which can replace string of input. My strategy is to find all indexes of source strings at first, and then replace them by target strings. I don't know how to replace string by index, so I just use the slice. However, if the length of target string doesn't equal to the source string, this program will be wrong. I want to know what's the way to replace string by index.
def tr(srcstr,dststr,string):
indexes = list(find_all(string,srcstr)) #find all src indexes as list
for index in indexes:
string = string[:index]+dststr+string[index+len(srcstr):]
print string
tr('aa','mm','aabbccaa')
the result of this will be right: mmbbccmm
but if tr('aa','ooo','aabbccaa'), the output will be wrong:
ooobbcoooa
Upvotes: 1
Views: 5737
Reputation: 1021
def tr(srctr, deststr, string):
string = string.split(srctr)
return ''.join([deststr if i == '' else i for i in string ])
print tr('aa', 'ooo', 'aabbccaa') # ooobbccooo
Upvotes: 0
Reputation: 3522
Python strings are immutable (as far as I can remember), so you can't just go in and insert stuff.
Luckily Python already has a replace()
function.
>>> s = "hello, world!"
>>> s1 = s.replace("l", "k")
>>> print s1
hekko, workd!
Upvotes: 3
Reputation: 1447
Are you aware of the str.replace method? I think it will do what you're wanting:
http://docs.python.org/library/string.html#string.replace
And when you find that you're wanting to support more than simple string replacement, check out the re module:
http://docs.python.org/library/re.html
Upvotes: 0