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
Python's comprehension and generator expressions are quite powerful.
You can do the vowel removal the same time as you do the join():
>>> volString = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}
>>> s = 'accveioub'
>>> ''.join(c for c in s if c not in volString)
'ccvb'
In fact you do the swap in the join() too but this maybe a little too verbose:
>>> ''.join('v' if c == 'b' else 'b' if c == 'v' else c for c in s if c not in volString)
'ccbv'
You could pull out the swap code into a mapping dict (dict.get(k, v) returns v if k is not in the dictionary):
>>> vbmap = {'b': 'v', 'v': 'b'}
>>> ''.join(vbmap.get(c, c) for c in s if c not in volString)
'ccbv'
The advantage being these solutions avoid all the intermediate string creations.