1

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

3 Answers 3

3

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!
Sign up to request clarification or add additional context in comments.

1 Comment

@remy Has your question been answered? If so, you can accept an answer using the green check mark.
0

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

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.