tags:

views:

5159

answers:

7

Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?

Maybe like myString[2:end]?

EDIT: If leaving the second part means 'till the end', if you leave the first part, does it start from the start?

+19  A: 
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
Paolo Bergantino
oo, I was about to add more examples, but I see it was done for me. Thank you kind sir.
Paolo Bergantino
+2  A: 

Yes there is. Your example is very close:

myString[2:]
Jarret Hardie
+1  A: 

myString[2:] .. leave off the second index to go to the end

eduffy
+1  A: 

mystring[2:]

Vasil
+1  A: 

You've got it right there except for "end". Its called slice notation. Your example should read.

new_sub_string = myString[2:]

If you leave out the second param it is implicitly the end of the string.

bouvard
+6  A: 

Besides the direct answer that others have given, you can find all the other rules for slicing behavior explained in the Strings section of the official tutorial.

DNS
+1: for having a link to more information :-)
tgray
+1  A: 

One example seems to be missing here: full (shallow) copy.

>>> x = "Hello World!"
>>> x
'Hello World!'
>>> x[:]
'Hello World!'
>>> x==x[:]
True
>>>

This is a common idiom for creating a copy of sequence types (not of interned strings). [:] Shallow copies a list, See python-list-slice-used-for-no-obvious-reason.

gimel
Does this create a new copy?
Joan Venge
A new copy will be created for lists - see edited answer.
gimel