1

I am finding slicing in Python a bit very difficult. Lets say if I want the first five and last five characters of a phrase to display how do i go about it. For example:

words = input("Enter a word ")
slice = words[:2]
print(slice)
Evan Carslake
  • 2,267
  • 15
  • 38
  • 56
paapame
  • 11
  • 3
  • 3
    Possible duplicate of [Explain Python's slice notation](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) – NightShadeQueen Oct 03 '15 at 19:50

1 Answers1

2

You can use negative indexing for slice from end :

>>> s="teststring"
>>> 
>>> s[-5:]
'tring'
>>> s[:5]
'tests'

Actually a slice notation observes the following law :

[start:end:step]

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

Read more about slicing https://docs.python.org/2/tutorial/introduction.html#strings

And https://docs.python.org/2.3/whatsnew/section-slices.html

Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • thank you but how can I add both the [-5] and [ :5] in one rather than two separates. Thank you – paapame Oct 03 '15 at 19:27
  • @paapame You can not do it just with slicing but you can remove the string from index `x` to `-x` with replacing it with empty string `''`. `>>> s.replace(s[3:-3],'') 'tesing' ` – Mazdak Oct 03 '15 at 19:32
  • @Thank you for your help, you have been very helpful to me – paapame Oct 03 '15 at 19:34
  • you are awesome look at this: Enter a word IamGoing TotheSuperMarket IamGo arket – paapame Oct 03 '15 at 19:50