在 Python 中切片字符串时如何使用变量作为索引?
我一直在尝试使用循环从字符串中切出两个字符,但它不是抓取两个字符,而是只抓取一个。
我已经尝试过:
input[i:i+1]
但
input[i:(i+1)]
似乎都不起作用。
如何使用变量进行切片?
完整的例程:
def StringTo2ByteList(input):
# converts data string to a byte list, written for ascii input only
rlist = []
for i in range(0, len(input), 2):
rlist.append(input[i:(i+1)])
return rlist
I've been trying to slice two characters out of a string using a loop, but instead of grabbing two characters, it only grabs one.
I've tried:
input[i:i+1]
and
input[i:(i+1)]
but neither seems to work.
How do I use a variable for slicing?
The full routine:
def StringTo2ByteList(input):
# converts data string to a byte list, written for ascii input only
rlist = []
for i in range(0, len(input), 2):
rlist.append(input[i:(i+1)])
return rlist
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
切片值不是切片的起始和结束字符,而是起始点和结束点。如果您想对两个元素进行切片,那么停止点必须比开始点大2。
The slice values aren't the start and end characters of the slice, they're the start and end points. If you want to slice two elements then your stop must be 2 greater than your start.
记住切片索引的一个好方法是将数字视为元素之间位置的标签。
例如,要切片
ba
,您可以使用fruit[0:2 ]
。当以这种方式思考时,事情似乎不再违反直觉,并且您可以轻松避免在代码中出现相差一的错误。A nice way to remember slice indexing is to think of the numbers as labeling the positions between the elements.
So for example to slice
ba
you would usefruit[0:2]
. When thinking of it this way, things no longer seem counter-intuitive, and you can easily avoid making off-by-one errors in your code.当我们进行从左到右的迭代时,基于中间位置的推理是有效的:
因为 pos 2 位于 20 / 55 之间,而 pos 5 位于 75 / 120 之间
。
但当我们进行从右到左迭代时,它不起作用:
我们必须将 li[ 5 : 2 : -1 ] 视为:
从元素 li[5](即 120)直到未包含的元素 li[2](即 55)
也就是说
从元素 li[5](即 120)仅包含 li[3](即 65)。
。
这使得从最后开始进行危险的反向切片:
和
。
如果很难这样思考,防止错误的一种方法就是写
。
请注意,获得反向切片的唯一方法是包含第一个
元素
Reasoning on the basis of the in-between positions works when we do a left-to-right iteration:
because pos 2 is between 20 / 55 and pos 5 is between 75 / 120
.
But it doesn't work when we do right-to-left iteration:
We must think of li[ 5 : 2 : -1 ] as :
from element li[5] (which is 120) as far as uncomprised element li[2] (which is 55)
that is to say
from element li[5] (which is 120) only as far as li[3] included (which is 65) .
.
That makes dangerous reverse slicing from the very end:
and
.
In case of difficulty to think like that, a manner to prevent errors is to write
.
Note that the only way to obtain a reverse slicing as far as the first element INCLUDED is
that stands for