Changing multiple characters by other characters i

2020-03-24 03:15发布

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
>>> 

标签: python string
3条回答
forever°为你锁心
2楼-- · 2020-03-24 03:19

You should use intermediate replacement to get proper result in python:

s2.replace('b',' ')
s2.replace('v','b')
s2.replace(' ','v')

In other words steps are following

  1. Replace b to ' ' space
  2. Replace 'v' to 'b'
  3. Replace ' ' space (that was your b character) to 'v'

Good luck!

查看更多
霸刀☆藐视天下
3楼-- · 2020-03-24 03:27

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.

查看更多
对你真心纯属浪费
4楼-- · 2020-03-24 03:35

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

查看更多
登录 后发表回答