为什么要打印SPO?

2024-09-27 19:21:03 发布

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

>>> print("loops"[- 1:1:- 1]*2)
spospo
>>>

为什么输出不是slssls?你知道吗


Tags: printloopsslsslsspospo
1条回答
网友
1楼 · 发布于 2024-09-27 19:21:03
"loops"[-1:1:-1]

让我们检查一下slicing works

s[i:j:k] – slice of s from i to j with step k

If i or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.

The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

所以[-1:1:-1]意味着i = -1j = 1k = -1。你知道吗

i是负数,所以i = -1表示i = len(s) + (-1) = len(s) - 1len(s)5,因此我们得到以下切片:"loops"[4:1:-1]。你知道吗

根据上面的定义,我们现在使用以下索引来定义项:44 - 1 = 34 - 2 = 2。我们停在4 - 3 = 1因为那是我们的终点,我们不包括这一点。你知道吗

所以结果是索引4, 3, 2,也就是'spo'。你知道吗

最后,该字符串被2相乘,后者重复一次:'spospo'。你知道吗

相关问题 更多 >

    热门问题