首页 > 解决方案 > python中字符串的索引函数

问题描述

我正在尝试从头开始实现一个名为say“Function”的函数,该函数计算字母的每个参数z在字符串中顺序出现的次数。

例如, Function('abcbcb', z=2) 应该返回 ab:1, bc:2, cb: 2

或 Function('abcbcb', z=3) 应该返回 abc: 1, bcb: 2, cbc: 1

我曾尝试使用循环和 python 字符串方法,但我还不能编写一个有效的方法。

谢谢!

标签: pythonfunction

解决方案


首先让我们给这个函数起个名字,因为这个名字很容易混淆。我会称之为时间。
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)

推荐阅读