how to append semicolon to a variable
Bengt Richter
bokr at oz.net
Sat Aug 13 13:34:54 EDT 2005
On 13 Aug 2005 08:14:32 -0700, "yaffa" <yxxxxlxxxxx at gmail.com> wrote:
>dear folks,
>
>i have the following lines of python code:
>
> couch = incident.findNextSibling('td')
> price = couch.findNextSibling('td')
> sdate = price.findNextSibling('td')
> city = sdate.findNextSibling('td')
> strUrl = addr.b.string
>currently what this ends up doing is creating something like this
>
>couch3201/01/2004newyork
>
>now what i want to do is add a semicolon after the couch, price, sdate,
>city so that i get something like this
>
>couch;32;01/01/2004;new york
>
>does anyone know how to do this?
>
>thanks
>
>yaffa
>
>p.s. i tried couch = couch + ';' and then i tried couch = couch + ";"
>and then i tried couch = couch.append ';'
>
Assuming all your findNextSibling calls result in strings, as in
>>> couch = 'couch'
>>> price = '32'
>>> sdate = '01/01/2004'
>>> city = 'newyork'
>>>
You can put them in a list
>>> [couch, price, sdate, city]
['couch', '32', '01/01/2004', 'newyork']
And join them with a string inserted between each successive pair of elements
>>> ';'.join([couch, price, sdate, city])
'couch;32;01/01/2004;newyork'
If you like a space after each ';', just include it in the joiner string
>>> '; '.join([couch, price, sdate, city])
'couch; 32; 01/01/2004; newyork'
>>>
If all your items weren't string type, you'll have to convert first, e.g.,
>>> price = 32
>>> '; '.join([couch, price, sdate, city])
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: sequence item 1: expected string, int found
>>> '; '.join(map(str,[couch, price, sdate, city]))
'couch; 32; 01/01/2004; newyork'
If you have 2.4 and don't like map, you can use a generator expression:
>>> '; '.join(str(x) for x in (couch, price, sdate, city))
'couch; 32; 01/01/2004; newyork'
or if you want the quoted strings
>>> '; '.join(repr(x) for x in (couch, price, sdate, city))
"'couch'; 32; '01/01/2004'; 'newyork'"
Note: if you want ';' appended to each item instead of just between items, you
can just add ';' to the whole thing
>>> '; '.join(str(x) for x in (couch, price, sdate, city)) + ';'
'couch; 32; 01/01/2004; newyork;'
Which avoids the trailing blank you would get if you appended '; ' to every item
before joining them, as in
>>> ''.join(('%s; '%x) for x in (couch, price, sdate, city))
'couch; 32; 01/01/2004; newyork; '
or
>>> ''.join((str(x) + '; ') for x in (couch, price, sdate, city))
'couch; 32; 01/01/2004; newyork; '
HTH
Regards,
Bengt Richter
More information about the Python-list
mailing list