Python Forum
String slicing in python from reverse
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
String slicing in python from reverse
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 ?

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]
>>> 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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.

Possibly Related Threads…
Thread Author Replies Views Last Post
  printing a string in reverse Skaperen 2 223 Nov-20-2021, 05:08 AM
Last Post: ghoul
  I am trying to reverse a string using loop codinglearner 4 521 Sep-28-2021, 10:46 PM
Last Post: Pedroski55
  Reverse a String ragav_in 3 909 Jul-24-2020, 02:24 AM
Last Post: ragav_in
  String slicing and loop iteration divyansh 9 2,381 Jun-07-2020, 10:29 PM
Last Post: divyansh
  String slicing divyansh 6 1,444 May-31-2020, 06:15 AM
Last Post: pyzyx3qwerty
  string slicing help oli_action 2 940 Mar-22-2020, 09:57 AM
Last Post: oli_action
  Reverse the string word sneha 2 1,303 Dec-12-2019, 03:37 AM
Last Post: sneha
  Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) Drone4four 4 1,544 Aug-23-2019, 07:59 PM
Last Post: Drone4four
  Code Clean-up and Maya/Python Slicing issues mvvthology 1 1,222 Aug-05-2019, 10:43 PM
Last Post: Yoriz
  string slicing default value Uchikago 1 1,356 Jul-01-2019, 11:19 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020