gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:20:03 25 4
gpt4 key购买 nike

嗨,如果两个字母在字母表上相互跟随,我正在尝试打印出传递的字符串的子字符串。即 '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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com