Truncating a string in python

It's called slicing, read more about it e.g. here: http://docs.python.org/tutorial/introduction.html#strings


As @Uku and @thebjorn said its called Slicing

But one easier way to think is to consider a String like a list, for example you can do:

text = 'Any String'
for letter in text:
    print letter

And the same if you want to get a specific letter inside the string:

>> text = 'Any String'
>> text[4]
'S'

ps.: Remember that it's zero based, so text[4] return the 5th letter.

Using Slice it'll return a "substring" text[i:j] from your original String where "i" are the initial index (inclusive) and "j" are the end index (exclusive), for example:

>> text = 'Any String'
>> text[4:6] # from index 4 to 6 exclusive, so it returns letters from index 4 and 5
'St'
>> text[0:4]
'Any '
>> text[:4] # omiting the "i" index means i = 0
'Any '
>> text[4:] # omitting the "j" index means until the end of the string

A negative index is relative to the end of the String like making a substitution from the negative index to "len(text) + i".

In our case len(text) is 10, a negative index -1 will be like using text[9] to get the last element, -2 will return the last but one element and so forth.

In examples you sent, string[0:-3] should return everything but last 3 characters and string[3:-3] should return everything but first 3 and last 3.

Hope it helpped.


It's called a slice. From the python documentation under Common Sequence Operations:

s[i:j]

The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

source