python - 这个将 'string' 视为 'list' 的回文代码如何工作?

标签 python python-3.x string

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

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

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

最佳答案

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

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'

在您的情况下,如果步骤是-1,那么它会向后退:

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

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

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

关于python - 这个将 'string' 视为 'list' 的回文代码如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57944912/

相关文章:

python - 您可以动态地向对象添加属性吗?

python - 如何在 Cython 的 setup.py 中指定 Python 3 源?

python - Jupyter Notebook 无法打包 folium

java - 1 行中多个模式的正则表达式

c++ - 使用 getline 函数获取段错误?

python - 如何在 PySpark RDD 中返回不同的集合?

python - pandas - 包括所有列和行对值

python - 将one-hot编码维度转换为1的位置索引

python - 如何升级到最新的Anaconda 5.0.1

java - "Recursive"listToString()-链表中的方法