我正在尝试操纵一个字符串。
从一个字符串中提取所有元音后,我想用同一字符串中的所有'v'替换为'b',所有'b'替换为'v'(ig“ accveioub”首先将变为ccvb,然后变为ccbv)。
我在交换字符时遇到问题。我最终得到了ccvv,我想我会根据这段代码得到它。我正在考虑遍历字符串,并使用if语句基本上停留在索引i .equals“ v”处的字符,然后将其替换为“ b”,而else语句,将“ b”替换为“ v”,然后将字符追加或合并在一起?
这是我的代码
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
>>>
Run Code Online (Sandbox Code Playgroud)
实际上你已经完成了一半,唯一需要注意的是,当你想“交换”时string,你必须创建“临时”,string而不是直接替换。
你所做的是这样的:
ccvb
ccbb #cannot distinguish between what was changed to b and the original b
ccvv #thus both are changed together
Run Code Online (Sandbox Code Playgroud)
考虑使用 中不存在的字符作为string第一个替换。比方说,我现在首先更改所有b内容1:
s2 = s2.replace("b","1")
s2 = s2.replace("v","b")
s2 = s2.replace("1","v")
Run Code Online (Sandbox Code Playgroud)
然后你会得到:
ccvb #original
ccv1 #replace b with 1
ccb1 #replace v with b
ccbv #replace 1 with v
Run Code Online (Sandbox Code Playgroud)
这里最重要的一点是临时的使用string