返回给定字符串位置的重复计数
我需要程序返回我在python中重复索引字母的次数。举例来说,如果我给它:返回给定字符串位置的重复计数
numLen("This is a Test", 3)
我想它返回
3
因为s的说三次。 现在我只有:
def numLen(string, num):
for s in string:
print(s + ' ' + str(test.count(s)))
没什么,我知道,但我茫然的家伙。
你首先需要获得指定索引中的字符,然后返回计数:
def numLen(inputstring, index):
char = inputstring[index]
return inputstring.count(char)
演示:
>>> def numLen(inputstring, index):
... char = inputstring[index]
... return inputstring.count(char)
...
>>> numLen("This is a Test", 3)
3
Python的指标在零开始,所以第3位的是请在您的输入示例中输入s
。
我的印象是,使用'string'作为变量名是个不好的习惯,因为它是标准库中的一个众所周知的模块。 – Volatility 2013-04-21 21:35:48
@Volatility:也许;在名称选择中更新得更清楚一点。 – 2013-04-21 21:36:52
你应该照顾。实际上有一个字符串模块可以导入为:import string – 2013-04-21 21:41:51
def count_occurences(line, index): return line.count(line[index])
您的函数参数不匹配; 'test'在哪里定义? – 2013-04-21 21:29:38
'string.count(string [num])'应该可以工作。 – Blender 2013-04-21 21:29:46
你的代码中仍然有'test.count'试图修复。 :-) – 2013-04-21 21:35:07