简体   繁体   English

反向字符串切片在 Python 中如何工作?

[英]How does Reverse String Slicing works in Python?

I would like to know how does Reverse String Slicing works.我想知道反向字符串切片是如何工作的。 For example例如

name = 'Python'
print(name[4:1])

This code wouldn't give me any result, not even any error.这段代码不会给我任何结果,甚至没有任何错误。 What is actually happening here?这里实际发生了什么?

But if I write但如果我写

print(name[4:1:-1])

It will give the result as "oht"它会将结果显示为“oht”

1st example is not giving you any result, because you start off with index 4 and you want to go to index 1 (0, because 1 is excluded) - which is kind of impossible.第一个例子没有给你任何结果,因为你从索引 4 开始,你想 go 到索引 1(0,因为 1 被排除) - 这是不可能的。 Default step is 1.默认步长为 1。

2nd example starts from index 4, ends on index 1, which is excluded.第二个示例从索引 4 开始,以索引 1 结束,该索引被排除在外。 Step in this example is -1, that is why the result is 'oht'.此示例中的 step 为 -1,这就是结果为 'oht' 的原因。

index of 'Python':
0 1 2 3 4 5
P y t h o n

# 1 is excluded

Python slicing works that way: Python 切片是这样工作的:

name = 'Python'
print(name[start_from_index:go_to_index:step_of_slicing])

is that clear for you?你清楚吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM