How to get a substring with variable indices

Tim Chase python.list at tim.thechases.com
Mon Dec 18 08:39:29 EST 2006


> I have a string named text. I need to extract a substring from it 
> starting by variable 's' and ending by 'e'.
> 
> text[s:e] generates the following error:
> 
>     TypeError: slice indices must be integers or None

Your syntax is correct...the error you get back is the clue: 
either "s" or "e" fails to meet the criteria of being "integers 
or None".  Check your values/types of those two variables before 
this call and you'll likely find that one or both is some other 
data-type.

 >>> text="hello world"
 >>> s = 4
 >>> e = 5
 >>> text[s:e]
'o'

Darn those error messages that give away the answer... ;)

-tkc






More information about the Python-list mailing list