英文:
my very basic for loop for removing vowels from a text isn't working
问题
I'm doing the CS50P course as my first course in python and in Problem set 2 there was a problem about removing vowels from a given text
I tried doing
Vowels = ["A", "a", "E", "e", "U", "u", "O", "o", "I", "i"]
inputs = input("input: ")
outputs = inputs
for x in Vowels:
outputs.replace(x, "")
print(f"output: {outputs}")
but it didn't work
I've solved the problem in another way but I'm just curious why didn't my first attempt work
英文:
I'm doing the CS50P course as my first course in python and in Problem set 2 there was a problem about removing vowels from a given text
I tried doing
Vowels = ["A", "a", "E", "e", "U", "u", "O", "o", "I", "i"]
inputs = input("input: ")
outputs = inputs
for x in Vowels:
outputs.replace(x, "")
print(f"output: {outputs}")
but it didn't work
I've solved the problem in another way but I'm just curious why didn't my first attempt work
答案1
得分: 1
The replace function does not actually replace it, it just returns a string with the inputs replaced. So instead, you could write:
Vowels = ["A", "a", "E", "e", "U", "u", "O", "o", "I", "i"]
inputs = input("input: ")
outputs = inputs
for x in Vowels:
outputs = outputs.replace(x, "")
print(f"output: {outputs}")
英文:
The replace function does not actually replace it, it just returns a string with the inputs replaced. So instead, you could write:
Vowels = ["A", "a", "E", "e", "U", "u", "O", "o", "I", "i"]
inputs = input("input: ")
outputs = inputs
for x in Vowels:
outputs = outputs.replace(x, "")
print(f"output: {outputs}")
答案2
得分: 1
你需要在替换元音后重新分配值。因此,你的代码将是
outputs = outputs.replace(x, "")
replace函数不会修改原始字符串,而是返回修改后的字符串的副本。
英文:
You need to reassign the value, after replacing the vowel. So your code will be
outputs = outputs.replace(x, "")
The replace function doesn't modify the original string, instead it returns the copy of modifying string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论