编写一个接受以下内容的程序:
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() 方法在这里很有用。”
最佳答案
这里有几个注意事项:
- 使用
1 = s1.split(', ')
,您将split
的返回值分配给数字1
。您应该将其分配给一个有效的变量名,例如l
。 - 通常,逗号分隔的列表表示仅由逗号分隔的项目字符串,不包括空格,因此您应该使用
','
而不是', '
. - 使用
print(list.count(s2))
,您将调用list.count
方法作为未绑定(bind)的方法,但由于您正在尝试计数l
中s2
的出现,您应该将其作为l
的绑定(bind)方法来调用,如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
关于python-3.x - 打印第二个字符串在第一个字符串以逗号分隔的成员中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55111964/