[Tutor] no rsplit

Orri Ganel singingxduck at gmail.com
Sun Aug 21 19:45:20 CEST 2005


Jonas Melian wrote:

>v = "64x43x12"  -> '64x43', '12'
>
>How split it by the las 'x'?
>
>In 2.4 it could be used rsplit("x",1)
>
>but i've 2.3.5
>
>Is there another way of splitting a string from the end?
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
Well, if you want to have some fun with list comprehensions . . . :

 >>> v = "64x43x12"
 >>> [i[::-1] for i in v[::-1].split("x",1)[::-1]]
['64x43', '12']

On the other hand, if you're not as list comprehension happy as I am, 
you could write a function to do the same thing:

 >>> def rsplit(string, sep=" ", maxsplit=-1):
       string = string[::-1]
       stringlist = string.split(sep, maxsplit)
       stringlist = stringlist[::-1]
       for i in range(len(stringlist)):
             stringlist[i] = stringlist[i][::-1]
       return stringlist
 >>> rsplit(v, "x", 1)
['64x43', '12']     


-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.



More information about the Tutor mailing list