How do i iterate through a string and replace specific chars in python correctly?

13,506

Solution 1

One line solution:

print(''.join(char.get(s, s) for s in string))

if :

string = "Hello, my name is fesker"

char={"a":"o","e":"i","i":"u","o":"e","u":"a","H":"J"}

Detailed solution:

I have some suggestions for your code:

Don't use .replace() there it will replace all matching characters

Use dict instead of list there if you want key,value pair.
char={"a":"o","e":"i","i":"u","o":"e","u":"a","H":"J"}

second convert the string in list if you want to modify it because string are immutable.

string=list(string)

Here is your solution with some modification :

string = "Hello, my name is fesker"

char={"a":"o","e":"i","i":"u","o":"e","u":"a","H":"J"}

string=list(string)

for index,item in enumerate(string):
    for key,value in char.items():
        if item==key:
            string[index]=value

print("".join(string))

output:

Jille, my nomi us fiskir

Solution 2

Your Problem:

string = string.replace(string[i],chars[x][1]) <- this replaces ALL instances of the letter selected. So, in the string "Hello", the letter 'e' goes in this rotation 'e' -> 'i' -> 'u' -> 'a' -> 'o' -> 'e', so it appears to be unchanged, but it is actually been changed 5 times.

Possible Solutions:

Using Your example of "Hello" to replace "e" with "i":

  • If you want to replace just the n number of occurrences of the letter, you can use the 3rd argument to .replace(), which could be .replace("e", "i", 1). NOTE: this is probably the worst solution, but I mention it so you understand about how .replace() works.

  • You could replace one character at at time in a loop. In the examples below, of course substitute the numbers 1 and 2 with something like i and i + 1. If you select this solution, keep in mind, when you loop through your string or array, you will check each letter to see if it needs to be replace first. If it needs to be replaced, find the replacement character with O(1) lookup (using hash dictionary), then replace with one of these following examples.

Code:

string = "{}{}{}".format(string[:1], "i", string[2:])
  • Or you could turn your string into an array, which is mutable.

Code:

string = list(string)
# or string = [i for i in string]
# ["H", "e", "l", "l", "o"]
string[1] = "i"
# ["H", "i", "l", "l", "o"]
string = "".join(string)
# "Hillo"
  • Per Ayodhyankit Paul, you should definitely use a dictionary to store your pairs. Also, here is his 1 liner solution of the loop I explained and that he explained:

''.join(char.get(s, s) for s in string)

Share:
13,506

Related videos on Youtube

Eirik Fesker
Author by

Eirik Fesker

Updated on June 04, 2022

Comments

  • Eirik Fesker
    Eirik Fesker almost 2 years

    I am trying to make a kind of a pronounceable cryptographic language in python. I want to iterate through a string and change i.e. just some vowels.

    i thought this could be done with an array chars["a","o"]where the first letter should be replaced with the second one.

    I am experimenting with this code.

    import string
    
    string = "Hello, my name is fesker"
    chars =[
           ["a","o"],
           ["e","i"],
           ["i","u"],
           ["o","e"],
           ["u","a"],
           ["H","J"],
           ]
    
    for i in range(len(string)):
        print(string[i])
        replaced=False
    
        for x in range(len(chars)):
    
            if string[i] in chars[x][0] and replaced == False:
               string = string.replace(string[i],chars[x][1])
               replaced=True
               print("Replace",chars[x][0],"with",chars[x][1])
    
    
    print(string)
    

    I dont get the point, i think the function should be correct but string replace gives me a different output. The final sentence should be read as "Jille, my nomi us fosker"

    but the python shell gives me that "Jelle, my neme es fesker":

        H
    Replace H with J
    e
    Replace e with i
    l
    l
    o
    Replace o with e
    ,
    
    m
    y
    
    n
    a
    Replace a with o
    m
    i
    Replace i with u
    
    u
    Replace u with a
    s
    
    f
    a
    Replace a with o
    s
    k
    o
    Replace o with e
    r
    Jelle, my neme es fesker
    

    What am i doing wrong?

    • David John Coleman II
      David John Coleman II over 6 years
      string = string.replace(string[i],chars[x][1]) <- this replaces ALL instances of the letter selected. So, in the string "Hello", the letter 'e' goes in this rotation 'e' -> 'i' -> 'u' -> 'a' -> 'o' -> 'e', so it appears to be unchanged, but it is actually been changed 5 times.
  • David John Coleman II
    David John Coleman II over 6 years
    Your first solution is a great one liner!