You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CS50P PSET2:twttr项目中如何合并元音移除后的字符串

CS50P PSET2 问题解决:一次性移除所有元音

问题描述

我在完成CS50P的PSET2(Setting up my twttr)作业时,编写了如下Python代码:

vowel = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u"]

vowel_remove = input("Input: ")
print("Output: ", end="")

for vowels in vowel:
    lower_vowel = vowels.lower()
    # print(lower_vowel)
    if vowels in vowel_remove:
        print(vowel_remove.replace(vowels, ""))

print()

输入:

Input: Apple

得到输出:

Output: Appl
pple

目前代码会逐个移除字符串中的元音并多次输出,需要实现一次性移除所有元音的正确逻辑。

问题根源

你的代码每次循环都是基于原始输入字符串替换单个元音后直接打印,而不是在已处理的字符串基础上继续操作。比如输入"Apple"时,替换"A"得到"pple"、替换"e"得到"Appl",两次打印就导致了两行输出。

正确实现方案

方法一:逐个字符筛选非元音

遍历输入字符串的每个字符,只保留不是元音的字符,最后拼接成结果:

vowels = {"A", "E", "I", "O", "U", "a", "e", "i", "o", "u"}  # 集合查找效率更高
user_input = input("Input: ")
result = ""
for char in user_input:
    if char not in vowels:
        result += char
print(f"Output: {result}")

输入"Apple"时,输出Output: ppl,符合需求。

方法二:使用str.translate()(高效简洁)

通过创建转换表,一次性移除所有元音字符:

vowels = "AEIOUaeiou"
# 创建转换表:将所有元音映射为None(即删除)
trans_table = str.maketrans("", "", vowels)
user_input = input("Input: ")
result = user_input.translate(trans_table)
print(f"Output: {result}")

这种方法处理长字符串时效率更高,代码也更简洁。

方法三:基于原有思路修改(累积替换结果)

如果想沿用你原来的遍历元音的思路,需要每次替换后更新处理的字符串,最后只打印一次结果:

vowels = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u"]
user_input = input("Input: ")
result = user_input
for vowel in vowels:
    result = result.replace(vowel, "")
print(f"Output: {result}")

每次循环都在之前处理的结果上继续替换元音,最终得到移除所有元音的字符串,仅打印一次。

内容的提问来源于stack exchange,提问作者Osman Abuna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 01:05:04