MachineElf
MachineElf

Reputation: 1281

Slice to the end of a string without using len()

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?

Upvotes: 36

Views: 118015

Answers (8)

japamat
japamat

Reputation: 720

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.'

Upvotes: 1

seb_rc
seb_rc

Reputation: 43

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.

Upvotes: 2

Draganeel
Draganeel

Reputation: 1

word="Help" 
word[:]

'Help'

I hope this helps you

Upvotes: -3

Bob Baxley
Bob Baxley

Reputation: 3751

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'

Upvotes: 15

monkut
monkut

Reputation: 43832

Or even:

>>> word = "Help"
>>> word[-3:]
'elp'

Upvotes: 26

Rik Poggi
Rik Poggi

Reputation: 29302

Are you looking for this?

>>> word = "Help"
>>> word[1:]
'elp'

Upvotes: 3

Denis
Denis

Reputation: 7343

Yes, of course, you should:

word[1:]

Upvotes: 4

Uku Loskit
Uku Loskit

Reputation: 42040

You can instead try using:

word[1:]

Upvotes: 55

Related Questions