这是我的情况;我正在尝试制作一个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
?
如果有解决此问题的方法,将不胜感激。
最佳答案
您可以使用以下命令获取FINAL
,这会将每个不是元音的元素替换为“?”:
FINAL = ''.join(e if e in "AEIOU" else "?" for e in S)
您可以对代码进行一些改进。如果您使用的是Python 3,则
input
返回一个字符串,因此不需要强制转换,可以直接定义S
,如下所示:S = input("Enter A Word (CAPITALS ONLY):")
QUESTIONMARK = "?"
CONSONANTS = 'BCDFGHJKLMNPQRSTVXZ'
if any((C in CONSONANTS) for C in S):
FINAL = ''.join(e if e in "AEIOU" else "?" for e in S)
number_of_consonants = sum(1 for c in S if c in CONSONANTS)
print(FINAL)
else:
print('Not Found')
print(f'The original word is: {S}')
print(f'The word without consonants is: {FINAL}')
print(f'The number of consonants in the word are: {number_of_consonants}')
如果需要计算辅音的数量,可以使用以下内容
CONSONANTS = 'BCDFGHJKLMNPQRSTVXZ'
number_of_consonants = sum(1 for c in S if c in CONSONANTS)