34

With string indices, is there a way to slice to end of string without using len()?

Negative indices start from the end, but [-1] omits the final character.

word = "Help"
word[1:-1]  # But I want to grab up to end of string!
word[1:len(word)]  # Works but is there anything better?
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
MachineElf
  • 1,231
  • 2
  • 15
  • 28
  • 2
    This is covered in the Python tutorial and in SO's own [standard answer](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) for slice questions. – DSM Mar 18 '12 at 09:35
  • OK feel free to delete if it's spam! – MachineElf Mar 18 '12 at 09:45
  • Does this answer your question? [Understanding slicing](https://stackoverflow.com/questions/509211/understanding-slicing) – mkrieger1 Jul 14 '22 at 09:59

8 Answers8

52

You can instead try using:

word[1:]
Uku Loskit
  • 40,868
  • 9
  • 92
  • 93
26

Or even:

>>> word = "Help"
>>> word[-3:]
'elp'
monkut
  • 42,176
  • 24
  • 124
  • 155
14

I found myself needing to specify the end index as an input variable in a function. In that case, you can make end=None. For example:

def slice(val,start=1,stop=None)
    return val[start:stop]

word = "Help"
slice(word)  # output: 'elp'
Bob Baxley
  • 3,551
  • 1
  • 22
  • 28
4

Yes, of course, you should:

word[1:]
Denis
  • 7,127
  • 8
  • 37
  • 58
3

Are you looking for this?

>>> word = "Help"
>>> word[1:]
'elp'
Rik Poggi
  • 28,332
  • 6
  • 65
  • 82
2

You could always just do it like this if you want to only omit the first character of your string:

word[1:]

Here you are specifying that you want the characters from index 1, which is the second character of your string, till the last index at the end. This means you only slice the character at the first index of the string, in this case 'H'. Printing this would result in: 'elp'

Not sure if that's what you were after though.

seb_rc
  • 43
  • 3
1

Sometimes it is useful to save the index, for example to use it on other variables or to pass it to functions. Here, slice objects come in useful.

>>> word = "Help"
>>> index = slice(1,None) # equivalent to [1:] indexing
>>> word[index]
'elp'
>>> sentence = "Help with Python indexing."
>>> sentence[index]
'elp with Python indexing.'
japamat
  • 670
  • 5
  • 5
-2
word="Help" 
word[:]

'Help'

I hope this helps you

Tunaki
  • 132,869
  • 46
  • 340
  • 423