Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing multiple characters by other characters in a string [duplicate]

Tags:

python

string

I'm trying to manipulate a string.

After extracting all the vowels from a string, I want to replace all the 'v' with 'b' and all the 'b' with 'v' from the same string (i.g. "accveioub" would become ccvb first, then ccbv).

I'm having problem to swap the characters. I end up getting ccvv and I figured I'd get that based of this code. I'm thinking of iterating through the string and using an if statement basically staying if the character at index i .equals"v" then replace it with "b" and an else statement that says "b" replace it with "v" and then append or join the characters together?

Here's my code

def Problem4():
    volString = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
    s = "accveioub"
    chars = []
    index = 0

    #Removes all the vowels with the for loop
    for i in s:
        if i not in volString:
            chars.append(i)
    s2 = "".join(chars)
    print(s2)
    print(s2.replace("v", "b"))
    print(s2.replace("b", "v"))

>>> Problem4()
ccvb
ccbb
ccvv
>>> 
like image 967
Usman Bashiru Avatar asked Mar 05 '16 05:03

Usman Bashiru


People also ask

What can you replace couple of characters in a string with?

replace() String. replace() is used to replace all occurrences of a specific character or substring in a given String object without using regex.

How do I replace multiple characters in a string in SQL?

Using the REPLACE() function will allow you to change a single character or multiple values within a string, whether working to SELECT or UPDATE data.


1 Answers

You have done it half-way actually, the only thing to take note is that when you want to "swap" the string, you got to create "temporary" string instead of replacing is directly.

What you did was this:

ccvb 
ccbb #cannot distinguish between what was changed to b and the original b
ccvv #thus both are changed together

Consider using the non existent character in the string as the first replacement. Let say, I now change all b with 1 first:

s2 = s2.replace("b","1")
s2 = s2.replace("v","b")
s2 = s2.replace("1","v")

Then you will get:

ccvb #original
ccv1 #replace b with 1
ccb1 #replace v with b
ccbv #replace 1 with v

The most important point here is the use of the temporary string

like image 166
Ian Avatar answered Sep 30 '22 07:09

Ian