繁体   English   中英

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

[英]finding consecutive letters in a string python

嗨,如果两个字母在字母表上紧随其后,我正在尝试打印出传递字符串的子字符串。 即“asdfhi”-> 嗨

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

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 实际上提供了ord函数,该函数返回字符的整数表示,换句话说,您可以使用Ascii 表

订单()

给定一个长度为 1 的字符串,当参数是一个 unicode 对象时返回一个表示字符的 Unicode 码位的整数,或者当参数是一个 8 位字符串时返回字节的值

所以,你可以做这样的事情:

def consecultive(inp_str):
    for k, v in zip(inp_str, inp_str[1:]):
        if ord(v) - ord(k) == 1:
            yield k, v

a = 'asdfhi'
list(consecultive(a))

输出:

[('h', 'i')]

如果您只是修复缩进级别并从 while 语句中删除 =,您的函数就可以工作。 它永远循环的原因是因为您目前正在 while 循环之外增加计数。

s = 'asdfhi'

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) # h i

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM