通过切片了解字符串反转 [英] Understanding string reversal via slicing

查看:54
本文介绍了通过切片了解字符串反转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种向后打印字符串的方法,在google上快速搜索后,我找到了这个方法:

I was looking for a way to print a string backwards, and after a quick search on google, I found this method:

假设 a 是一个字符串变量.这将向后返回 a 字符串:

Suppose a is a string variable. This will return the a string backwards:

a[::-1]

谁能解释一下这是如何工作的?

Can anyone explain how that works?

推荐答案

当然,[::] 就是 扩展切片 运算符.它允许您使用子字符串.基本上,它的工作原理是将您想要的元素指定为 [begin:end:step],并且它适用于所有序列.关于它的两件事:

Sure, the [::] is the extended slice operator. It allows you to take substrings. Basically, it works by specifying which elements you want as [begin:end:step], and it works for all sequences. Two neat things about it:

  • 您可以省略一个或多个元素,它会做正确的事情"
  • begin、end 和 step 的负数是有意义的

对于begin和end,如果给出负数,则表示从序列的末尾开始计数.例如,如果我有一个列表:

For begin and end, if you give a negative number, it means to count from the end of the sequence. For instance, if I have a list:

l = [1,2,3]

那么l[-1]为3,l[-2]为2,l[-3]为1.

Then l[-1] is 3, l[-2] is 2, and l[-3] is 1.

对于 step 参数,负数意味着在序列中向后工作.所以对于一个列表::

For the step argument, a negative number means to work backwards through the sequence. So for a list::

l = [1,2,3,4,5,6,7,8,9,10]

您可以编写 l[::-1] 这基本上意味着在阅读列表时使用 -1 的步长.Python 在填写开始和停止时会做正确的事",因此它会向后遍历列表并为您提供 [10,9,8,7,6,5,4,3,2,1].

You could write l[::-1] which basically means to use a step size of -1 while reading through the list. Python will "do the right thing" when filling in the start and stop so it iterates through the list backwards and gives you [10,9,8,7,6,5,4,3,2,1].

我已经给出了带有列表的示例,但字符串只是另一个序列并且以相同的方式工作.所以 a[::-1] 的意思是通过连接你通过字符串向后走得到的字符来构建一个字符串.

I've given the examples with lists, but strings are just another sequence and work the same way. So a[::-1] means to build a string by joining the characters you get by walking backwards through the string.

这篇关于通过切片了解字符串反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆