简体   繁体   English

如何对字符串进行反向切片方法

[英]How to do reverse slicing method on a string

I have a alphabet string like: 我有一个像这样的字母字符串:

string = 'abcdefghijklmnopqrstuvwxyz'

if want to do slicing and and go from z to a but with 3 steps. 如果要进行切片,然后从z到a但有3个步骤。 what should I do? 我该怎么办? I know string[::-1] will reverse it but how can I make it go by 3 steps each time? 我知道string[::-1]会反转它,但是如何每次使它走3步呢?

I have done it by assigning a new string which is reverse of the other string and do slicing with 3 steps from there. 我通过分配一个与其他字符串相反的新字符串来完成此操作,并从那里开始用3个步骤进行切片。 I'm looking for a new way to do it without changing the previous string and doing it on the same spot 我正在寻找一种新的方法来执行此操作,而无需更改先前的字符串并在同一位置进行操作

The last number in the slice is the interval: 切片中的最后一个数字是间隔:

string = 'abcdefghijklmnopqrstuvwxyz'
string[::-3]
'zwtqnkheb'

If you want 3 letter slices starting from the end and going backward, you can use a list comprehension: 如果要从末尾开始向后三个字母切片,则可以使用列表理解:

string = 'abcdefghijklmnopqrstuvwxyz'
slices =  [ string[i:i+3][::-1] for i in range(len(string)-3,0,-3) ]

# ['zyx', 'wvu', 'tsr', 'qpo', 'nml', 'kji', 'hgf', 'edc']

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

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