【问题标题】:Finding how many different letters there are in a string in Python在 Python 中查找字符串中有多少个不同的字母
【发布时间】:2013-03-07 22:32:52
【问题描述】:

我对 Python 3 和编程非常陌生。我试图找到一种算法来找出一个句子何时是一个 pangram。借助 string 模块的一个函数,我已经解决了讨价还价的问题,但我还需要找出非 pangrams 中有多少不同的字母(已经将它们切换为小写)。

非常欢迎任何帮助。

【问题讨论】:

    标签: python string pangram


    【解决方案1】:

    试试看这组字母的长度:

    len(set(yourstring))
    
    
    In [8]: set('lowercase')
    Out[8]: set(['a', 'c', 'e', 'l', 'o', 's', 'r', 'w'])
    
    In [9]: len(set('lowercase'))
    Out[9]: 8
    

     

    不要忘记删除空格。

    In [10]: len(set('The quick brown fox jumps over the lazy dog'.lower().replace(' ', '')))
    Out[10]: 26
    

    【讨论】:

    • 标点符号是如何处理的?
    • @KyleStrand 你可以通过isalpha查看
    • 我使用了 string.punctuation。 for c in string.punctuation: ... line = line.replace(c, "")
    【解决方案2】:

    如果你不想计算标点符号,试试这个:

    s = "It's the economy, stupid!"
    t = set(c.lower() for c in s if c.isalnum())
    len(t) #returns 13
    

    或者,如果你只想要字母:

    s = "It's the economy, stupid!!!11!!"
    t = set(c.lower() for c in s if c.isalpha())
    len(t) #returns 13
    

    【讨论】:

      【解决方案3】:

      你可以试试这个:

      s = 'The quick brown fox jumps over the lazy dog'
      count = len(set(c.lower() for c in s if c != ' '))
      

      这里,计数将是 26。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        • 2015-11-26
        • 2019-11-03
        • 1970-01-01
        • 2020-03-20
        • 1970-01-01
        相关资源
        最近更新 更多