【问题标题】:Function that search for one character, then count how many times it appears Python [closed]搜索一个字符,然后计算它出现的次数 Python [关闭]
【发布时间】:2021-05-05 11:04:08
【问题描述】:

我是 python 新手,我正在寻找一个程序,要求用户填写一串字符(短语或其他),然后填写特定字符。

程序必须返回字符串中字符出现的次数。我需要使用 .count 函数,但我的代码无法正常工作。

欢迎任何帮助!

def search(text,character):
    '''This function searches for one character, defined as 2nd argument, 
    in a given text / string of characters, defined as 1 st argument, 
    and counts how many times it appears'''
    
    #The 1st argument text here represents the input in which you are looking for
    text = input("Type here the text you want: ")
    
    #The 2nd argument character represents the character you are looking for
    character = input("Type the character you want to count: ")
        
    
    
    text.count('character')
    print text.count

【问题讨论】:

    标签: python string input count character


    【解决方案1】:

    有你想要的代码,
    我创建了一个带有两个参数的函数搜索:

    • text 我搜索的字符串
    • 字符我要数的字符串

    然后我将字符的出现次数存储在字符串文本中并打印出来

    def search(text,character):
        '''This function searches for one character, defined as 2nd argument, 
        in a given text / string of characters, defined as 1 st argument, 
        and counts how many times it appears'''
        
        occ = text.count(character)
        print("Occurences:",occ)
    
    #The 1st argument text here represents the input in which you are looking for
    text = input("Type here the text you want: ")
    
    #The 2nd argument character represents the character you are looking for
    character = input("Type the character you want to count: ")
    search(text,character)
    

    【讨论】:

    • 原始功能要求您只返回它,而不是打印它。由于我在回答中提到的可重用性原因,将其打印在函数中将是一个坏习惯。
    【解决方案2】:

    在您的代码中,您应该将 text.count(character) 保存在一个变量中,然后打印该变量。您没有看到任何内容,因为您没有打印正确的内容。 此外,您应该将变量字符放在 count 中,而不是字符串 'character'

    var = text.count(character)
    print var
    

    【讨论】:

      【解决方案3】:

      根据您的规范,该函数只返回值,不打印。作为最佳实践,函数应该只做一件事。这将提高它们的可重用性。如果您还要在函数内部打印出现次数,那将限制您可以使用该函数的其他地方。

      在这里我输入了一个字符串和一个字符,然后我使用我的函数找出了该字符在字符串中出现的次数:

      def search(text, character):
      count = 0
      
      # for every c (stands for character) in text    
      for c in text:
          if c == character:
              count += 1
              
      return count
      
      txt = input('Enter text: ')
      ch  = input('Enter character: ')
      
      print('Number of occurrances: ', search(txt, ch))
      

      请注意,您也可以将search(txt, ch) 保存在cnt = search(txt, ch) 等变量中,以便以后使用。您也可以使用您的变量进行打印,例如print('Number of occurrances: ', cnt)

      【讨论】:

      • 我认为更简单的方法是:sum([c==character for c in text])
      • 这增加了一个概念,因此增加了程序的复杂性。我认为初学者目前不需要。初学者应该一次处理一件事。有很多方法可以做到这一点,但这可能是最明确和最容易理解的一种。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 2021-07-06
      • 2023-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多