How to slicing a list element (get the substring of a list element)?
lijst = ('123-Abc','456-Def','789-Ghi') print "lijst = " + lijst print "lijst[4:] = " + lijst[4:] print "lijst[4:1] = " + lijst[4:1]
has this output:
lijst = 456-Def lijst[4:] = Def lijst[4:1] =
?? i had hoped that last line to be "D" !
So what is the correct syntax in order to get a substring from a list element? (i'm running python 2.7.3 on a raspberry pi)
The correct syntax for slicing is [start:stop] and not [start:count] the way that it was used in the question. So you are actually looking for lijst[4:4+1] or lijst[4:5] for your last line.
There are all sorts of nice reasons for having this. You can use the same index to split a string into two parts, for example
lijst[:4] = "456-" lijst[4:] = "Def"
lijst[:4] + lijst[4:] == lijst
Note how you can leave out the first or last entry to indicate either the start or the end of the string.
Another nice feature of using indices like this is that the length of the string is given by stop-start. So
lijst[2:6] = "6-De"
and the length of this substring is 6 - 2 = 4
One last note is that you can also skip entries in the string by adding another step index:
lijst[0:7:2] = "46Df"
This goes from the start (index 0) to the end (index 7) and shows every second entry. Since you can leave out the start and the end indices, this is equivalent to
Getting a substring between the indices a and b (excluding b) is achieved using the slice [a:b]. And to get the character at index i you simply use [i] (think of the string as an array of characters).
>>> test = "456-Def" >>> test[4:5] 'D' >>> test[4:8] 'Def' >>> test 'D'