首页 > 解决方案 > 尝试制作一个用“?”替换辅音词的 Python 程序 基于用户输入

问题描述

这是我的情况;我正在尝试制作一个 python 程序,它接受用户输入并检测任何辅音('B、C、D、F、G、H、J、K、L、M、N、P、Q、R、S、T、 V, X, Z') 在用户输入的字符串中,然后用“?”替换所述字母 象征。连同打印原始单词和找到的辅音数量。

示例输出:

Please enter a word or zzz to quit: Dramatics
The original word is: dramatics
The word without consonants is: ??a?a?i??
The number of consonants in the word are: 6

我的代码:

 C =  input("Enter A Word (CAPITALS ONLY):")
 S = str(C)
 QUESTIONMARK = str("?")
 chars = str('B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, X, Z')
 if any((C in chars) for C in S):
     FINAL = str.replace(QUESTIONMARK,str(S),chars)
     print(FINAL)
 else:
     print('Not Found')

我的输出:

这是运行 Python 3.7 的 WING Pro 上返回的内容:

 Enter A Word (CAPITALS ONLY):HELLO
 ?

如果有任何解决此问题的方法,将不胜感激。

标签: python

解决方案


you could do it with a list comprehension:

vowels='aeiou'
word = input('Please enter a word or zzz to quit: ')
print('The original word is: '+word.lower())
masked = ''.join([l if l.lower() in vowels else '?' for l in word])
print('The word without consonants is: '+masked)
print('The number of consonants in the word are: '+str(masked.count('?')))

output:

Please enter a word or zzz to quit: Dramatics
The original word is: dramatics
The word without consonants is: ??a?a?i??
The number of consonants in the word are: 6

推荐阅读