在python中删除字符和反转字符串

2024-09-30 12:33:25 发布

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

我必须写一个程序,在其中你把两个字,并作出一个如果声明,当第一个字是第二个字颠倒,没有第一个和最后一个字符。我有s2[1:-1:-1]==s,但我不明白这怎么不起作用,因为s2[1:-1]==s在我输入lian和pliant时起作用。另外,如果删除一个字符,我还必须编写另一个带有for循环和两个拼接的程序来确定一个单词是否与另一个单词相同。i、 e.splender=苗条。有什么提示吗


Tags: 程序声明for字符单词s2苗条lian
2条回答
def comp_words(longerW, shorterW):
    # compare if removing a char from first word can make it identical to second word
    return any(longerW[:i] + longerW[i+1:]  ==  shorterW for i, c in enumerate(longerW))

你必须记住切片操作符[start:finish]在Python中,从开始到结束。考虑以下几点:

>>>'hello'[1:-1]
'ell'
>>>'hello'[-2, 0, -1]
'lle'

当你倒退的时候,你需要从另一端开始

编辑:或者,如果你想少一点聪明,你可以这样做

>>>'hello'[1:-1][::-1]
'lle'

相关问题 更多 >

    热门问题