James
James

Reputation: 63

Python replacing string given a word

Hi does anyone know how to make a function that replaces every alphabetic character in a string with a character from a given word (repeated indefinitely). If a character is not alphabetic it should stay where it is. Also this has to be done without importing anything.

def replace_string(string,word)
'''
>>>replace_string('my name is','abc')
'ab cabc ab'

So far i come up with:

def replace_string(string,word):
    new=''
    for i in string:
        if i.isalpha():
            new=new+word
        else: new=new+i
    print(new)

but, this function just prints 'abcabc abcabcabcabc abcabc' instead of 'ab cabc ab'

Upvotes: 1

Views: 96

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336078

If you can't use the itertools module, first create a generator function that will cycle through your replacement word indefinitely:

def cycle(string):
    while True:
        for c in string:
            yield c

Then, adjust your existing function just a little bit:

def replace_string(string,word):
    new=''
    repl = cycle(word)
    for i in string:
        if i.isalpha():
            new = new + next(repl)
        else: 
            new = new+i
    return new

Output:

>>> replace_string("Hello, I'm Greg, are you ok?", "hi")
"hihih, i'h ihih, ihi hih ih?"

Another way to write this (but I think the first version is more readable and therefore better):

def replace_string(string,word):
    return ''.join(next(cycle(word)) if c.isalpha() else c for c in string)

Upvotes: 0

user2390182
user2390182

Reputation: 73450

Change as follows:

def replace(string, word):
    new, pos = '', 0
    for c in string:
        if c.isalpha():
            new += word[pos%len(word)]  # rotate through replacement string
            pos += 1  # increment position in current word
        else: 
            new += c
            pos = 0  # reset position in current word
    return new

>>> replace('my name is greg', 'hi')
'hi hihi hi hihi'

Upvotes: 1

Related Questions