[Tutor] handling string!!

Karl Pflästerer sigurd at 12move.de
Thu Oct 23 12:24:39 EDT 2003


On 23 Oct 2003, Mehta, Anish <- Anish.Mehta at enst-bretagne.fr wrote:

> str = 'ABC   value="123" value="345"'

`str' is a builtin.  Don't use it as variable.

> i have a string and i want to extract the values between the
> quotes(""). Like 123, 345

> Do we have some builtin function to handle this.

Not exactly.  If youre string is always in the way you described it,
then there is an easy possibilty.

You could transform the string in a list with the `split()' function and
use `"' as delimiter.

In [7]: s = 'ABC   value="123" value="345"'

In [8]: s.split('"')
Out[8]: ['ABC   value=', '123', ' value=', '345', '']


Now the only problem is to grab the first, third ... value from the
list.

In [9]: sp = s.split('"')

In [10]: for i in range(1, len(sp), 2):
   ....:     print sp[i]
   ....:
123
345


That's a bit ugly and in Python 2.3 with the itertools module we have a
better alternative.

In [17]: from itertools import islice

In [18]: for i in islice(sp, 1, None, 2):
   ....:     print i
   ....:     
123
345



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list