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
  Python3 string slicing Luchano55 4 602 Feb-17-2024, 09:40 AM
Last Post: Pedroski55
  Am I wrong or is Udemy wrong? String Slicing! Mavoz 3 2,536 Nov-05-2022, 11:33 AM
Last Post: Mavoz
  printing a string in reverse Skaperen 2 1,543 Nov-20-2021, 05:08 AM
Last Post: ghoul
  I am trying to reverse a string using loop codinglearner 4 2,160 Sep-28-2021, 10:46 PM
Last Post: Pedroski55
  Reverse a String ragav_in 3 2,186 Jul-24-2020, 02:24 AM
Last Post: ragav_in
  String slicing and loop iteration divyansh 9 4,718 Jun-07-2020, 10:29 PM
Last Post: divyansh
  String slicing divyansh 6 3,353 May-31-2020, 06:15 AM
Last Post: pyzyx3qwerty
  string slicing help oli_action 2 2,183 Mar-22-2020, 09:57 AM
Last Post: oli_action
  Reverse the string word sneha 2 2,620 Dec-12-2019, 03:37 AM
Last Post: sneha
  Accepting strings as arguments when slicing a string? (Ziyad Yehia on Udemy) Drone4four 4 3,783 Aug-23-2019, 07:59 PM
Last Post: Drone4four

Forum Jump:

User Panel Messages

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