string.upto() and string.from()

Kent Johnson kent at kentsjohnson.com
Wed Mar 22 11:19:31 EST 2006


Fredrik Lundh wrote:
> ikshefem at gmail.com wrote:
> 
> 
>>I often need to re-code for myself a small code snippet to define
>>string.upto() and string.from(), which are used like :

FWIW this is pretty easy to do with str.split() and rsplit():
>>
>># canonical examples
>>
>>>"1234456789".upto("45")
>>
>>'1234'

"1234456789".split("45", 1)[0]
'1234'
>>
>>>"123456dd987".from('d')
>>
>>'d987'

"1234456789".rsplit("45", 1)[-1]
'6789'

>>
>># if not found, return whole string
>>
>>>"hello, world !".upto("#")
>>
>>"hello, world !"


"hello, world !".split("#", 1)[0]
'hello, world !'

>>
>>>u"hello, world !".from("#")
>>
>>u"hello, world !"

"hello, world !".rsplit("#", 1)[-1]
'hello, world !'

Kent



More information about the Python-list mailing list