【问题标题】:prints the number of occurances of the second string within the first string's comma-separated members打印第一个字符串逗号分隔成员中第二个字符串的出现次数
【发布时间】:2019-03-11 23:36:50
【问题描述】:

编写一个程序,接受:

s1 逗号分隔的字符串 s2 要计数的字符串 并打印第二个字符串在第一个字符串的逗号分隔成员中出现的次数。

例如,如果用户输入一、二、一、三然后是一,您的程序应该打印 2。提示:您会发现方法 list.count() 在这里很有帮助。您应该使用的 input() 语句和相关的字符串处理已在下面的示例代码中提供。 (注意:假设用户输入的系列中的每个逗号后面都有一个空格。)

这是我目前所拥有的:

# split on comma + space to create the list
s1= input('Please enter a series of comma-separated strings: ')
# split on comma + space to create the list
1 = s1.split(', ')
# input the string to count in the list
s2 = input('Please enter a string to count: ')
# print out the number of times s2 occurs in s1
print(list.count(s2))

我得到了一个他们正在寻找的示例,但仍然没有完全理解这个概念。这是他们给我的:“例如,如果用户输入一、二、一、三,然后是一,您的程序应该打印 2。提示:您会发现方法 list.count() 在这里很有帮助。”

【问题讨论】:

    标签: python-3.x string list


    【解决方案1】:

    这里有几个注意事项:

    • 使用1 = s1.split(', '),您将split 的返回值分配给数字1。您应该将其分配给一个有效的变量名,例如 l
    • 通常,逗号分隔的列表是指仅由逗号分隔的项目字符串,不包括空格,因此您应该使用 ',' 而不是 ', ' 分隔。
    • 使用print(list.count(s2)),您将list.count 方法作为未绑定方法调用,但是由于您尝试计算ls2 的出现次数,您应该将其作为绑定方法调用l 改为 l.count(s2)

    通过以上修改,您的代码应如下所示:

    s1= input('Please enter a series of comma-separated strings: ')
    l = s1.split(',')
    s2 = input('Please enter a string to count: ')
    print(l.count(s2))
    

    示例输入/输出:

    Please enter a series of comma-separated strings: one,two,three,one
    Please enter a string to count: one
    2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      相关资源
      最近更新 更多