tseries
tseries

Reputation: 783

How do this variant of reverse at python?

example at command line linux

echo fc67e62b625f33d7928fa1958a38a353085f0097cc22c08833850772035889b8 | grep -o .. | tac | paste -sd '' -

I try find how do this at python but notting . what i am trying to do - i try reverse every line at text by this rule. Only what i find is

txt = "Hello World"[::-1]
print(txt)

example ABCDEF

echo ABCDEF | grep -o .. | tac | paste -sd '' -

will give EFCDAB

this

txt = "ABCDEF"[::-1]
print(txt)

return FEDCBA

Upvotes: 1

Views: 96

Answers (3)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48590

You can do this all with a single line with list comprehension.

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

print(chunkReverse('ABCDEF', 2)) # EFCDAB

Explanation

  1. The following function will chunk the string into partitions of size 2.
result = [s[i:i+n] for i in range(0, len(s), n)] # [ 'AB', 'CD', 'EF' ]
  1. Next, it will reverse the order of the tokens.
result = result[::-1] # [ 'EF', 'CD', 'AB' ]
  1. Finally, it will join them back together.
''.join(result) # EFCDAB

Upvotes: 1

Fisnik Hoxha
Fisnik Hoxha

Reputation: 11

I think this is an appropriate solution:

sample_string = "ABCDEFG"
string_length = len(sample_string)
reversed_string = sample_string[string_length::-1]
print(reversed_string)

Upvotes: 1

Mureinik
Mureinik

Reputation: 310983

If I understand correctly, you want to split the string to pairs of two characters, and then reverse the order of those pairs.

You can use re to split the string to pairs like that, and then use the slicing syntax to reverse their order, and join them again:

import re
source = 'ABCDEF'
result = ''.join(re.split('(.{2})', source)[::-1])

Upvotes: 1

Related Questions