【问题标题】:pythonic way to count total number of letters in string in pythonpythonic方法来计算python中字符串中的字母总数
【发布时间】:2020-09-18 09:32:32
【问题描述】:

我刚开始学习python,我能想到两种方法来计算字符串中的字母(忽略数字、标点和空格)

  1. 使用 for 循环:
for c in s:
    if c.isalpha():
        counter += 1
print(counter)
  1. 创建一个字母列表并计算列表的长度:(它会创建一个不需要的列表)
import re
s = "Nice. To. Meet. You."
letters = re.findall("([a-z]|[A-Z])", s)
counter = len(letters)
print(counter)

谁能告诉我有没有一种“pythonic”的方式来达到同样的效果? 像单行代码或调用的函数将返回一个 int 答案? 非常感谢。

【问题讨论】:

    标签: python string methods


    【解决方案1】:

    您的第一种方法是完全 Python 的,并且可能是要走的路。您可以稍微简化一下,使用filter 或列表理解为:

    s = "Nice. To. Meet. You."
    len(list(filter(str.isalpha, s)))
    # 13
    

    或者:

    len([i for i in s if i.isalpha()])
    # 13
    

    您的第二种方法并不是真正可取的,因为您实际上并不需要为此使用正则表达式。请注意,顺便说一下,您可以将该模式简化为 ([a-zA-Z])

    【讨论】:

    • 据我所知,没有我们可以调用的方法或函数吗?比如:xxxx(s) 返回一个 int?
    • 什么意思?有i.isalpha(),但你必须将它应用于每个字符@heihei
    • 对不起,我错过了那条线,我认为len([i for i in s if i.isalpha()]) 已经是最好的方法了。非常感谢。
    【解决方案2】:

    您可以使用正则表达式删除任何不是字母的内容,然后计算字符串的长度:

    import re
    s = "Nice. To. Meet. You."
    counter = len(re.sub(r'[^a-zA-Z]','',s))
    

    【讨论】:

    • @JvdV,谢谢!我将答案更新为仅使用字母
    • 谢谢你,另一种巧妙的方法!
    猜你喜欢
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2015-12-01
    • 2016-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多