Archive for the ‘Python’ Category

h1

Python substring

October 17, 2009

This page goes into more detail about halfway down (search for ‘Strings can be subscripted’), but this will be a general overview so I don’t have to go to that when I need to get a substring in Python.

This is the string I’ll work with:
strKami = "Kami"
+---+---+---+---+
| K | a | m | i |
+---+---+---+---+
0   1   2   3   4
-5 -4  -3  -2  -1

So unlike C++, characters are not referred to as a particular index of a string (i.e., strKami[0] == ‘K’), but as the space between two indexes.

strKami[0:1] == 'K'
strKami[-3:-1] == 'mi'
strKami[2:] == 'mi'
strKami[:2] == 'Ka'
strKami[3:243] == 'i' # "an index too large is replaced by the string size" (i.e., 243 is replaced by 4)
strKami[3:2] == '' # if lower bound > upper bound, returns empty string
strKami[243:] == '' # there is nothing here, so empty string

Follow

Get every new post delivered to your Inbox.