Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string slice indices - slice to end of string

Tags:

python

string

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? 
like image 205
MachineElf Avatar asked Mar 18 '12 09:03

MachineElf


People also ask

How do you slice a string at an index in Python?

Strings in python support indexing and slicing. To extract a single character from a string, follow the string with the index of the desired character surrounded by square brackets ([ ]), remembering that the first character of a string has index zero.

How do you slice a string in Python from the end?

The slicing starts with the start_pos index (included) and ends at end_pos index (excluded). The step parameter is used to specify the steps to take from start to end index. Python String slicing always follows this rule: s[:i] + s[i:] == s for any index 'i'.

Can we slice string in Python?

Python string supports slicing to create substring. Note that Python string is immutable, slicing creates a new substring from the source string and original string remains unchanged.

How do you slice a character in a string in Python?

Slicing Strings You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string.


1 Answers

You can instead try using:

word[1:] 
like image 187
Uku Loskit Avatar answered Sep 18 '22 00:09

Uku Loskit