我的用于从文本中删除元音字母的非常基本的for循环不起作用。

huangapple go评论56阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月6日 03:55:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定