Substring command for Python

Slices can be used to reproduce the substring function that other languages offer.

myString = “12345”

myString[:2] would produce “12”

myString[ 2:-2] would produce “3”

myString[2:5] would produce “345”

myString[2:4] would produce “34”

Advertisements

5 thoughts on “Substring command for Python

  1. Hi there, the best example I can give you comes pretty much from the official python docs website. http://docs.python.org/tut/node5.html see the section on strings

    There is an example there where they number the string using positive and negative numbers, it makes it very easy to understand.

    Here is how I understand it;
    s = “string”

    Then draw this on a piece of paper

    …….s…..t…….r……i…….n…..g
    ….0……1……2…..3……4……5
    ..-6….-5….-4….-3….-2….-1

    s[0] should equal “s” (the value up and to the right)
    s[2] should equal “r” (the value up and to the right)
    s[-1] should equal “g” (the value up and to the right)
    With the colon
    s[-5:-3] should equal “tr” (start at “t” and go to but not including “i” )
    s[2:5] should equal “rin” (start at “r” and go to but don’t include “g” )
    Now for the tricky bit
    s[-2:] should equal “ng” (the last 2 characters)
    s[:-2] should equal “stri” (everything except the last two chars)
    s[:2] should equal “st” (the first two characters)
    s[2:] should equal “ring” (everything but the first two chars)

    Hope this helps, but seriously check out the official python docs, covers everything.
    Cheers
    Tim and Bron

  2. @techteam: The numbering you have done: In positive numbers, it has seven positions. Somehow, you say 2 to 5 will be “rin”. That means 0 to 6 will just read 5 characters? What does 6 stand for then?? Please would you elaborate?

    • Hi
      Yeah no problems… well the six should not be there really. Sorry to confuse you. It is more of a guide to show you how the sequential numbers relate to the letters in the list.
      Yeah so the 6 is redundant I will take it out.
      Thanks
      Tim

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s