首页 > 解决方案 > 这个将“字符串”视为“列表”的回文代码如何工作?

问题描述

我发现了一个很棒的回文代码,我可以抽象地理解,但我不确定它是如何工作的。

def palindrome(word):
    return word == word[::-1]

我认为单词的数据类型是“字符串”而不是“列表”。但在该代码中,它将 word 视为列表类型。它会自动更改wordlist(word)吗?

标签: pythonpython-3.xstring

解决方案


Python 切片表示法非常简单。取自另一个答案

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array
a[start:stop:step] # start through not past stop, by step

举个例子:

word = 'abcd'

assert word[0] == 'a'
assert word[0:3] == 'abc'
assert word[0:4] == 'abcd'
assert word[0:4:2] == 'ac'

在你的情况下,如果 step 是-1那么它会倒退:

assert word[::-1] = 'dcba'

因此,如果一个单词 back 等于单词本身,那么它是回文:

if word == word[::-1]:
    return True

推荐阅读