找到一个字符串,其反向也出现在句子中[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我需要在一个句子中查找字符串,其反向也出现在同一个句子中并返回该字符串。

假设句子是:

幻觉永远不会变成真正清醒的东西,我可以看到完美的天空撕裂你有点晚了我已经撕裂了

在这里,我们可以看到"see""ees"相反

所以输出应该是"see"

请指导我如何做到这一点。

python python-3.x
2个回答
0
投票

使用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)

输出:

['see']

0
投票

你可以试试这个。

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) + "'")

输出:

'see' is the reverse of 'ees'
'ees' is the reverse of 'see'

您也可以按照@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) + "'")

输出:

'see' is the reverse of 'ees'
'ees' is the reverse of 'see'
© www.soinside.com 2019 - 2024. All rights reserved.