python - python 查找字符串中的连续字母

标签 python python-3.x string recursion

嗨,如果两个字母在字母表上相互跟随,我正在尝试打印出传递的字符串的子字符串。即 'asdfhi' -> hi

这是我到目前为止所拥有的。我试图递归地编写这个函数,但似乎无法让该函数迭代字符串。我知道我做错了请帮忙。目前,该函数只是使用第一组下标进行无限循环,并输出检查字符串中前两个字母的结果,但永远不会离开该状态。

def findSubstr(s):
    count=1
    while len(s) >= count:
        alpha='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        alphaIndex = alpha.index(s[count])
        #print(s[count-1])
        #print(alpha[alphaIndex-1])
        #print(s[count-1] == alpha[alphaIndex-1])
        if(s[count] in alpha):
            if(s[count-1] == alpha[alphaIndex-1]):
                print(s[count-1], s[count])
    count=count+1
    findSubstr(s)

最佳答案

您不必遍历字符串,让 python 为您做这件事——它更快、更有效。试试这个:

from string import ascii_letters

def find_consecutive(s) :
    for a,b in zip(ascii_letters, ascii_letters[1:]) :
        if a+b in s :
            print( a, b)

测试:

>>> find_consecutive('asdfhi')
h i
>>>

关于python - python 查找字符串中的连续字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59019914/

相关文章:

C# - 求和列表<string[]>

python - BeautifulSoup - 在看似简单的情况下解析问题

python - 基于python中的模板 header 合并多个csv文件

python - FileNotFoundError "try .. except IOError"未捕获时如何处理?

python - 解析不同格式的时间

python - Python中有 `string.split()`的生成器版本吗?

java - Golang 中的拆分器

Python 将列表中的元素与上一个和下一个元素进行比较

javascript - 如何将变量发送到JavaScript?

python - 更改 numpy 结构化数组 dtype 名称和格式