Python Forum
String slicing in python from reverse - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: String slicing in python from reverse (/thread-17918.html)



String slicing in python from reverse - ift38375 - Apr-29-2019

Hi,
I am newbie in this python fourm portal and need some help from experts side.
Suppose i declare string variable i.e name = "david" and perform name[0:3]
then it prints "dav". But when i was trying to declare name[3:0] then it shows blank ?
how can i take output as "vad" ?
is it possible or not ?


KS


RE: String slicing in python from reverse - perfringo - Apr-29-2019

With code name[3:0] you give Python an order: "give me letters on indices starting from 3 up to 0 which is first to be excluded". As you can't go up 3 -> 0 then there is no slice.

In order to go 'down' you must instruct Python to do so, and also keep in mind that last indice in slice will be excluded:

>>> name = 'david'
>>> name[2:0:-1]     # -1 instructs Python to 'step down'
'va'                 # letter with index 0 is excluded
>>> name[2::-1]
'vad'
>>> name[2:None:-1]  # this is same as previous but with explicit None
More information about slicings in Python documentation:

Documentation >>> Glossary >>> slice
Documentation >>> The Python Standard Library >>> Built-in Functions >>> slice()
The Python Language Reference >>> 6. Expressions >>> 6.3. Primaries >>> 6.3.3. Slicings