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
#1
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
Reply
#2
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
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reverse a String ragav_in 3 751 Jul-24-2020, 02:24 AM
Last Post: ragav_in
  String slicing and loop iteration divyansh 9 2,028 Jun-07-2020, 10:29 PM
Last Post: divyansh
  String slicing divyansh 6 1,215 May-31-2020, 06:15 AM
Last Post: pyzyx3qwerty
  string slicing help oli_action 2 832 Mar-22-2020, 09:57 AM
Last Post: oli_action
  Reverse the string word sneha 2 1,148 Dec-12-2019, 03:37 AM
Last Post: sneha
  Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) Drone4four 4 1,279 Aug-23-2019, 07:59 PM
Last Post: Drone4four
  Code Clean-up and Maya/Python Slicing issues mvvthology 1 1,067 Aug-05-2019, 10:43 PM
Last Post: Yoriz
  string slicing default value Uchikago 1 1,160 Jul-01-2019, 11:19 AM
Last Post: perfringo
  string slicing Uchikago 2 1,106 Jun-28-2019, 06:35 AM
Last Post: perfringo
  Slicing Python list of strings into individual characters Drone4four 5 1,636 Apr-17-2019, 07:22 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

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