简体   繁体   English

如何通过Python字符串切片用stride反转字符串

[英]How to reverse string with stride via Python String slicing

I need to reverse an interleaved string, means i have 2-pairs which shouldt get messed up like this: 我需要反转一个交错的字符串,意味着我有2对,应该像这样搞砸了:

>>> interleaved = "123456"

reversing 倒车

>>> print interleaved[::-1]
654321

but what i actually want is 但我真正想要的是

563412

is there a string slice operation for this? 这有一个字符串切片操作?

For even length strings this should do it: 对于偶数长度的字符串,这应该这样做:

>>> s = "123456"
>>> it = reversed(s)
>>> ''.join(next(it) + x for x in it)
'563412'

For odd length strings, you need to prepend the first character separately: 对于奇数长度的字符串,您需要分别添加第一个字符:

>>> s = "7123456"
>>> it = reversed(s)
>>> (s[0] if len(s)%2 else '') + ''.join(next(it) + x for x in it)
'7563412'

Using slicing and zip : 使用切片和zip

>>> s = "7123456"
>>> (s[0] if len(s)%2 else '') + ''.join(x+y for x, y in zip(s[-2::-2], s[::-2]))
'7563412'

The shortest way as far as I know would be to use a regex: 据我所知,最短的方法是使用正则表达式:

import re
''.join(re.findall('..?', '123456', flags=re.S)[::-1])
  • Input: '123456' 输入:'123456'
  • Output: '563412' 输出:'563412'

This also works for odd-length strings without having to implement separate logic for them. 这也适用于奇数长度的字符串,而不必为它们实现单独的逻辑。

You can bring several ideas to split a string in pieces and then reverse each piece and reassemble (join) the list reversed too. 您可以带几个想法将一个字符串分成部分 ,然后反转每个部分并重新组合(加入)列表反转。

Eg (using satomacoto answer in a not-so-readable way...) 例如(以不太可读的方式使用satomacoto答案......)

''.join([a[::-1][i:i+2][::-1] for i in range(0, len(a), 2)]) 

or (using FJ answer) 或(使用FJ答案)

''.join(map(''.join, zip(*[iter(a)]*2))[::-1])

and so on. 等等。 (Being a your string). (作为a你的字符串)。

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

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