0

Can any one please explain me why this prints none for the first statement where it says "university"? The second command prints index(-5) and index(3) which is cd but the first one gives me back nothing.

x = "university"
print(x[-5:4])
x = "abcdefg"
print(x[-5:4])
Wolf
  • 9,679
  • 7
  • 62
  • 108

3 Answers3

0

You print out slices of strings which start at index -5 and end at index 4. Slicing differs from single-element access (x[i]) not only in one or more colons (:) being involved, but in so far as you specify a range with a start index and an end index (start is inclusive whereas end isn't). The range [-5:4] is empty for "university" and contains two elements for "abcdefg".

See for illustration the content of the strings in relation to indices:

0  1  2  3 ]4
u  n  i  v  e  r  s  i  t  y
             [-5 -4 -3 -2 -1
0  1  2  3 ]4
a  b  c  d  e  f  g
    [-5 -4 -3 -2 -1

... which make it obvious that that the substring for university must be empty.

What you, probably, might be expecting is a 4-character substring beginning at index -5 which can be achieved by x[-5,-1].

Wolf
  • 9,679
  • 7
  • 62
  • 108
0

In the string "university" the index -5 is 'e' but index 4 is 'r'. If you print the values

x = "university"
print(x[-5:])
print(x[:4])

You get

rsity
univ

It's because the indexes aren't on the letters, but between the letters. so you get "unive||rsity" with | being an index.

PythonSnek
  • 542
  • 4
  • 21
0

In print(x[-5:4]) function, the first index -5 indicate "r" and second index 4 indicate "e" so first index was greater than the second index at the position of string.

However, in case of x= "university", the starting index are larger in position, so there is no overlapping section, so no value is output.

If you fix it with print(x[-9:4]) it will out put 'niv'.

I hope that it will help you.

thanks

  • Thank You, I think I got it now when we slice starting from negative index to positive, it prints the intersection that they cross each other. I appreciate all your responses. In the case of university staring from -5 backward and starting from 0 going forward. They don't cross each other. it basically prints the intersection. – Girma Moges Mar 14 '21 at 17:39