Prith Jaganathan
Prith Jaganathan

Reputation: 25

How to add strings with each other during a loop?

For my programming class, I need to a create a program that takes in a string and two letters as an argument. Whenever the first letter appears in the string, it is replaced with the second letter. I can do this by making the final string into a list. However, our professor has stated that he wants it to be a string, not a list. The code shown below is what I used to make the program work if the final result was to appear in a list.

def str_translate_101(string, x, y):
    new_list = []
    for i in string:
        if i == x:
            new_list.append(y)
        if i != x:
            new_list.append(i)
    return new_list     

I tried to make one where it would output a string, but it would only return the first letter and the program would stop (which I'm assuming happens because of the "return")

def str_translate_101(string, old, new):
    for i in string:
        if i == old:
            return new
        else:
            return i

I then tried using the print function, but that didn't help either, as nothing was outputted when I ran the function.

def str_translate_101(string, old, new):
    for i in string:
        if i == old:
            print(new)
        else:
            print(i)

Any help would be appreciated. An example of how the result should work when it works is like this:

str_translate_101('abcdcba', 'a', 'x') ---> 'xbcdcbx'

Upvotes: 2

Views: 83

Answers (2)

DaCruzR
DaCruzR

Reputation: 407

The simplest solution would be, instead of storing the character in a list you can simply declare an empty string and in the 'if' block append the character to the string using the augmented '+=' operator. E.g. if i == x: concat_str += y

As for the return, basically, it will break out of the for loop and return to where the function was called from. This is because it only has 1 objective, which once achieved it will not bother to process any further code and simply go back to where the function was called from.

Upvotes: 0

Daniel
Daniel

Reputation: 42748

You can use join to merge a list into a string:

def str_translate_101(string, x, y):
    new_list = []
    for i in string:
        if i == x:
            new_list.append(y)
        else:
            new_list.append(i)
    return ''.join(new_list)

or use the one-liner

str_tranlsate_101 = str.replace

Upvotes: 3

Related Questions