list comprehension
Peter Otten
__peter__ at web.de
Mon May 10 02:52:35 EDT 2004
Tim Roberts wrote:
> Guy Robinson <guy at NOSPAM.r-e-d.co.nz> wrote:
>
>>This works I was just wondering if something could be written more
>>concisely and hopefully faster:
>>
>>s = "114320,69808 114272,69920 113568,71600 113328,72272"
>>e = s.split(' ')
>>out =''
>>for d in e:
>> d =d.split(',')
>> out +='%s,%d ' %(d[0],-int(d[1]))
>>print out
>
> Well, why not the more obvious: s.replace(',',',-')
But beware negative numbers:
>>> int("--1")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): --1
>>>
Therefore at least
>>> "123,234 567,-789".replace(",", ",-").replace("--", "")
'123,-234 567,789'
>>>
As to robustness, the OP relying on commas not being followed by a space
seems dangerous, too, if the original data is created manually.
Peter
More information about the Python-list
mailing list