Thursday, April 14, 2011

Is there a way to substring a string in Python?

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?

From stackoverflow
  • >>> 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.
  • Yes there is. Your example is very close:

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

  • mystring[2:]

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

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

    tgray : +1: for having a link to more information :-)
  • 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.

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

0 comments:

Post a Comment