0

What is happening here? It won't pick up the exclamation mark in reverse indexing without a kludge.

h = str("Hello, World!")
print(len(h))
print(h[-13:-1]) #What happened to the !
print(h[-13:-1]+h[-1])
print(len(h[-13:-1]+h[-1]))​

Output: 13 "Hello, World" "Hello, World!" 13

DenDx
  • 11
  • 2
  • It is not broken. Python slices are closed to the left and open to the right, i.e. `13:-1` includes `13` and excludes `-1`. If you want "from "-13 til the end", simply use `h[-13:]` – rafaelc Dec 06 '19 at 20:01
  • The first index is inclusive, the second index is exclusive. If you want the rest of the string, just do: `h[-13:]`. – Gillespie Dec 06 '19 at 20:02
  • [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – Gillespie Dec 06 '19 at 20:03
  • Thank you. RafaelC got it first and correctly, but there is no upvote button for his reply. This board is still a mystery to me. One time I hit the down arrows to move down the page. Some people got upset. Anyway, thanks for your help people. Hope I don't get kicked for saying thank you incorrectly. – DenDx Dec 06 '19 at 20:20

1 Answers1

0

Slice indexing is inclusive in front, and exclusive in back. For example,

h = "Hello, World!"
print(h[3:6])
# 'lo,'

includes indices 3, 4, and 5, but not 6.

When you do [13:-1], you're grabbing everything from index 13 to index -1, but not index -1 itself. To get "everything after 13", you can just leave the second field in the slice blank:

print(h[8:])
# 'orld!'

You can do the same to get "every character before index 8":

print(h[:8])
# 'Hello, W'

and leaving both fields blank actually just produces a copy of the thing you're trying to slice:

print(h[:])
# 'Hello, World!'
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53