在python中使用范围和负步骤时字符串拼接的问题

2024-05-15 16:20:44 发布

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

我在玩python字符串拼接,遇到了一个python的行为,我不明白。假设您有一个字符串,它以三种不同的方式拼接:

str = "stackoverflow"

splicedStr = str[2:6]
#this spliced string would equal 'ackove'

splicedStr = str[2:8:2]
#this spliced string would equal 'akv'

splicedStr = str[2:8:-2]
#this spliced string would equal ''

我理解前两个。但是,在最后一个例子中,如果步数为负,为什么不等于'vka'?你知道吗


Tags: 字符串string方式equalthisstackoverflow例子str
2条回答

如果您正在从后面读取项目,那么如何访问后面的项目,然后访问前面的项目。你知道吗

这样做:

str = "stackoverflow"
splicedStr = str[8:2:-2]

你到底是什么正在执行:- 接头str=str[2:8:-2]

's', 't', 'a', 'c', 'k', 'o', 'v', 'e', 'r', 'f', 'l', 'o', 'w'
           !                             !!      
           # strat here                  # upto here

       # but stepsize is -2 so how it can proceed to Offlimit

你要找的是:

>>> s[-7:1:-2]
'vka'

这也是:

>>> s[6:1:-2]
'vka'

请注意,您总是从提供的第一个索引开始,一直到达到(或大于)提供的第二个索引为止。第三个指标是步幅。你知道吗

在您的例子中,您从8开始(它已经大于2),因此您以一个空字符串结束。你知道吗

我想你已经预料到了,如果步幅是负的,第一个索引应该是字符串右侧的位置。这不是从字符串左侧开始计算负索引的情况。你知道吗

像往常一样,the official language reference比我能更正式(更正确)地陈述它。你知道吗

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.

相关问题 更多 >