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
>>>
You should use intermediate replacement to get proper result in python:
In other words steps are following
Good luck!
Python's comprehension and generator expressions are quite powerful.
You can do the vowel removal the same time as you do the
join()
:In fact you do the swap in the
join()
too but this maybe a little too verbose:You could pull out the swap code into a mapping dict (
dict.get(k, v)
returnsv
ifk
is not in the dictionary):The advantage being these solutions avoid all the intermediate string creations.
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:
Consider using the non existent character in the
string
as the first replacement. Let say, I now change allb
with1
first:Then you will get:
The most important point here is the use of the temporary
string