在字符串 Python 中计算元音 [英] Count Vowels in String Python

查看:63
本文介绍了在字符串 Python 中计算元音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算字符串中特定字符出现的次数,但输出错误.

这是我的代码:

inputString = str(input("请输入一句话:"))一个=一个"A = "A"e = "e"E = "E"我 = "我"我 = "我"o = "o"O = "O"你 = "你"U = "U"计数 = 0计数 = 0计数 = 0计数 = 0计数 = 0如果 A 或 a in stri :acount = acount + 1如果 E 或 e 在 stri :ecount = ecount + 1如果我或我在 stri :icount = icount + 1如果 o 或 O 在 stri :ocount = ocount + 1如果 u 或 U in stri :ucount = ucount + 1打印(acount,ecount,icount,ocount,ucount)

如果我输入字母 A,输出将是:1 1 1 1 1

解决方案

你想要的可以很简单地完成:

<预><代码>>>>mystr = input("请输入一句话:")请输入一句话:abcdE>>>打印(*地图(mystr.lower().计数,aeiou"))1 1 0 0 0>>>

如果你不知道它们,这里是 map* 上的一个.

I'm trying to count how many occurrences there are of specific characters in a string, but the output is wrong.

Here is my code:

inputString = str(input("Please type a sentence: "))
a = "a"
A = "A"
e = "e"
E = "E"
i = "i"
I = "I"
o = "o"
O = "O"
u = "u"
U = "U"
acount = 0
ecount = 0
icount = 0
ocount = 0
ucount = 0

if A or a in stri :
     acount = acount + 1

if E or e in stri :
     ecount = ecount + 1

if I or i in stri :
    icount = icount + 1

if o or O in stri :
     ocount = ocount + 1

if u or U in stri :
     ucount = ucount + 1

print(acount, ecount, icount, ocount, ucount)

If I enter the letter A the output would be: 1 1 1 1 1

解决方案

What you want can be done quite simply like so:

>>> mystr = input("Please type a sentence: ")
Please type a sentence: abcdE
>>> print(*map(mystr.lower().count, "aeiou"))
1 1 0 0 0
>>>

In case you don't know them, here is a reference on map and one on the *.

这篇关于在字符串 Python 中计算元音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆