[英]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.