String concatenation

Paul Rubin http
Fri Apr 2 03:02:21 EST 2004


"Leif B. Kristensen" <junkmail at solumslekt.org> writes:
> Having recently started with Python, I've written this little function
> to retrieve place parts from a database and concatenate them to a
> string. While it certainly works, and is also considerably shorter than
> the PHP code that I originally wrote, I'm pretty convinced that there
> should be an even better way to do it. Can anybody show me how to write
> the string concatenation part in a more Pythonesque syntax?
> ...
>     for i in range(5):
>         tmp = res[i]        
>         if tmp[:1] != '-' and len(tmp) != 0:
>             place = place + ', ' + (res[i])
>     return place[2:]

Not tested:

  tmp = [x for x in res if x and x[0] != '-']
  return ', '.join(tmp)

Explanation: 

1) you can use "for x in res" instead of looping through range(5),
since you know that res has 5 elements (from the sql result).

2) x[:1] is the same as x[0] as long as x has at least 1 char (otherwise
   it throws an exception)

3) To prevent the exception, test for x being nonempty BEFORE examining x[0]

4) sep.join(stringlist) is the standard way to join a bunch of strings
   together, separated by sep.



More information about the Python-list mailing list