Python 返回给定字符串位置的重复计数
我需要程序返回我给出的索引的字母在python中被重复的次数。例如,如果我给它:Python 返回给定字符串位置的重复计数,python,repeat,Python,Repeat,我需要程序返回我给出的索引的字母在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
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)
演示:
Python索引从零开始,因此位置3是输入示例中的字母
s
。def count\u occurrences(line,index):返回line.count(line[index])
您的函数参数不匹配;哪里定义了test
?string.count(string[num])
应该可以工作。您的代码中仍然有test.count
试图修复。:-)我的印象是,使用string
作为变量名是不好的做法,因为它是标准库中众所周知的模块。@Volatility:也许;更新后的名称选择更加明确。您仍应小心。实际上有一个字符串模块可以导入为:importstring@5T41N5:是的,这就是我和波动性所讨论的。@MartijnPieters谢谢你,兄弟
>>> def numLen(inputstring, index):
... char = inputstring[index]
... return inputstring.count(char)
...
>>> numLen("This is a Test", 3)
3