0

Here as we can see in the image when we slice the string from 0:len(s) we are getting the full string, but when I try to print s of len (s) instead of getting the last character it throws me n error. I'm new to python so have some mercy! thanks!!

s='hello'
print(s[0:len(s)])
print(s[len(s)])

ddejohn
  • 8,775
  • 3
  • 17
  • 30
PvC9966
  • 7
  • 3
  • It's a classic off-by-one issue: slices will exclude the position after the `:`, and the positions are numbered from `0` to `len(s)-1` – Adam Smooch Sep 05 '21 at 18:22
  • Does this answer your question? [Python saying string index is out of range when I verified that it isn't](https://stackoverflow.com/questions/33735397/python-saying-string-index-is-out-of-range-when-i-verified-that-it-isnt) – ddejohn Sep 05 '21 at 18:24

1 Answers1

0

The string length is always 1 more than the max index since index is starting from 0 for single character while length starts with 1 for single character.
Please change your code to be like this:

s='hello'
print(s[0:len(s)-1])
print(s[len(s)-1])
Unused hero
  • 307
  • 1
  • 9