在senten中找到一个反向的字符串

2024-06-28 10:58:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要找到一个句子中的字符串,它的反向也出现在同一个句子中,然后返回该字符串。在

假设句子是:

illusion never changed into something real wide awake and i can see the perfect sky ees torn you are a little late I'm already torn

这里我们可以看到"see"有一个相反的"ees"

所以输出应该是"see"

请指导我怎么做。在


Tags: and字符串realcansomething句子widesee
2条回答

你可以试试这个。在

mystr = "illusion never changed into something real wide awake and i can see the perfect sky ees torn you are a little late I'm already torn"

def reverse(word):
    letter = list(word)
    length = len(letter)
    y = []
    for x,w in enumerate(letter):
        y.append("".join(letter[(length-1)-x]))
    return("".join(yy for yy in y))


words = mystr.split()
for word in words:
    if (reverse(word)) in words and len(word) > 1:   # len(word)>1 is for ignoring a word that contains only one letter, e.g. 'I' and 'a'.
        print ("'" + word + "' is the reverse of '" + reverse(word) + "'")

输出:

^{pr2}$

您也可以尝试@Nuhman建议的更简单的方法。在

mystr = "illusion never changed into something real wide awake and i can see the perfect sky ees torn you are a little late I'm already torn"

words = mystr.split()
for word in words:
    if word[::-1] in words and len(word) > 1:
        print ("'" + word + "' is the reverse of '" + reverse(word) + "'")

输出:

^{pr2}$

使用word[::-1]反转单词,如果单词列表中存在反转,则将其另存为list。在

hello = "illusion never changed into something real wide awake and i can see the perfect sky ees torn you are a little late I'm already torn"

words = hello.split(" ")

reverse_words = []
for word in words:
    if word[::-1] in words and len(word)>1 and word[::-1] not in reverse_words:
        reverse_words.append(word)

print(reverse_words)

输出:

^{pr2}$

相关问题 更多 >