0

I am new in Python 3. Today while reading about python reverse string using list I came to know an in-place slicing technique. The code looks like this:

s = input("Enter a string:\n")
''.join([ s[x:x+2][::-1] for x in range(0, len(s), 2) ])

I want to know how applying second in-place slice s[x:x+2][::-1] working for the pairwise character swap? For other languages, using [something] [something] denotes 2D array interpretation. How this is reversing the sliced pair?

Can you please explain? Thanks in advance.

Arif Hamim
  • 59
  • 7

1 Answers1

0

The slicing works like this :

[start:stop:step]

Now, let's take your code.

s[x:x+2][::-1] for x in range(0, len(s), 2)

s[x:x+2] 

this part takes the string starting with x index till x+1 index. There is no reversing and only slicing.


[::-1]

this part takes the sliced string you got from above and again slices the whole string back [since there is no start and stop, hence the whole string], but the third parameter tells it how many steps to take for slicing. Here it is -1, it means it will take last element and traverse it back which results in a reversed string.

PS : Your code doesn't do the reversing of string though as mentioned in comments by @kaya.

gsb22
  • 2,112
  • 2
  • 10
  • 25
  • Thanks for your answer. But I'm stuck with the second `[::-1]` part. For example, in C++, `[i] [j]` means we are iterating over a 2D array element. Is it a case for python that using `[i] [j]` means it will first iterate over _i_ then _j_ will iterate over the result of _i_? – Arif Hamim Mar 22 '20 at 13:29
  • no, if you write something like `a[2][3]` in python, it means same as what you have in C++. But when you add `:` part, this is specific to python and would do the slicing of string, from `start`:`stop` – gsb22 Mar 22 '20 at 13:32