计算没有元音的字符串长度(Count length of string without vowels)

编程入门 行业动态 更新时间:2024-10-25 12:27:16
计算没有元音的字符串长度(Count length of string without vowels)

我有一个字符串: -

a = 'abcderui'

我想计算字符串的长度减去元音。 实现这一目标的最佳目标是什么?

目前我在做: -

a = list(a) for i in a: if i in vowels: continue count +=1

I've a string:-

a = 'abcderui'

I want to count the length of the string a minus the vowels. What would be the fasstest wat to implement that?

Currently I'm doing:-

a = list(a) for i in a: if i in vowels: continue count +=1

最满意答案

如果字符串不是很大,那么str.translate是最好的选择:

>>> a = 'abcderui' >>> len(a.translate(None, 'aeiou')) 4

时序:

>>> a = 'abcderui'*100 >>> %timeit len(a.translate(None, 'aeiou')) 1000000 loops, best of 3: 1.86 µs per loop >>> %timeit sum(1 for c in a if c not in 'aeiou') 10000 loops, best of 3: 53.2 µs per loop >>> %timeit len(nonvowels.findall(a)) 10000 loops, best of 3: 65.3 µs per loop >>> %timeit len(vowels.sub('', a)) 10000 loops, best of 3: 72 µs per loop

If strings are not huge then str.translate is the best option:

>>> a = 'abcderui' >>> len(a.translate(None, 'aeiou')) 4

Timings:

>>> a = 'abcderui'*100 >>> %timeit len(a.translate(None, 'aeiou')) 1000000 loops, best of 3: 1.86 µs per loop >>> %timeit sum(1 for c in a if c not in 'aeiou') 10000 loops, best of 3: 53.2 µs per loop >>> %timeit len(nonvowels.findall(a)) 10000 loops, best of 3: 65.3 µs per loop >>> %timeit len(vowels.sub('', a)) 10000 loops, best of 3: 72 µs per loop

更多推荐

本文发布于:2023-04-29 09:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335881.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元音   字符串   长度   Count   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!