1

How to reverse "groups" (not list) of strings? For example I would like to convert "123456789" into "321654987" given that the "group" size equals to 3.

Followings are my code but it turns out to print empty strings:

string = "12345678901234567890"
new_string = ""
for i in range(0, len(string), 5):
    new_string = new_string + string[i:i+5:-1]
print (new_string)

Thanks for any input and advice.

3 Answers 3

2

When using a negative step, swap the start and end values too:

new_string += string[i + 4:i - 1 if i else None:-1]

Note that the end value is excluded, and None should be used to include the first character (-1 would slice from the end again and thus string[4:-1:-1] would be empty).

Demo:

>>> string = "12345678901234567890"
>>> new_string = ""
>>> for i in range(0, len(string), 5):
...     new_string = new_string + string[i + 4:i - 1 if i else None:-1]
... 
>>> new_string
'54321098765432109876'

However, it may be easier to first slice, then reverse, and save yourself the headaches of such slicings:

new_string += string[i:i + 4][::-1]
Sign up to request clarification or add additional context in comments.

Comments

1

A simple one liner for your problem would go something like.

>>> from itertools import chain
>>> testString = "123456789"
>>> group = 3
>>> "".join(chain.from_iterable([reversed(elem) for elem in zip(*[iter(testString)]*group)]))
'321654987'

Another Example ->

>>> testString = "12345678901234567890"
>>> group = 5
>>> "".join(chain.from_iterable([reversed(elem) for elem in zip(*[iter(testString)]*group)]))
'54321098765432109876'

2 Comments

It seems like unless you know you only want a specific length, the itertools method is the best.
Why? Many of these solutions can be passed the length as a parameter.
1

This can be done in one line:

newline = ''.join([string[i:i+n:1][::-1] for i in range(0, len(string), n)])

Where n is the size of the "group". In your case, it would be 3. An Explanation is below:

i in range(0, len(string), n) is responsible for counting by three

string[i+i+n:1] is responsible for getting each chunk

[::-1] will reverse each chunk

''.join() joins each now-reversed chunk back into a single string.

Another option is:

''.join([string[i+n-1:i-1 if i else None:-1] for i in range(0, len(string), n)])

Where the selecton and reversing is done in one step.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.