![](/img/trans.png)
[英]Replace a word in a String by indexing without “string replace function” -python
[英]Indexing function for a string in python
我正在尝试从头开始实现一个名为“功能”的 function,它计算每个字母参数 z 在字符串中顺序出现的次数。
例如, Function('abcbcb', z=2) 应该返回 ab:1, bc:2, cb: 2
或 Function('abcbcb', z=3) 应该返回 abc: 1, bcb: 2, cbc: 1
我尝试过使用循环和 python 字符串方法,但我还不能编写一个有效的方法。
谢谢!
首先让我们将 function 称为另一个名称,因为这个名称令人困惑。 我会称之为时间。
iterable[n:k]
将返回从索引 n(包括)到索引 k(不包括)的迭代。
这是一个带有解释的代码:
def times(str, z):
dict ={} # we create an empty dict
for i in range(len(str)-z+1): #we loop over the string a number of times depending on z so we can check all z length paramters
if str[i:i+z] in dict.keys(): #if the part of the string is in the keys of the dictionary then we add one
dict[str[i:i+z]] += 1
else:
dict[str[i:i+z]] = 1 # if it wasn't we set it to one
return dict
times('abcbcb',3)
对不起英语,它对我来说是第二语言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.