[Python] Python and concatenating strings
horst
horsu at freeshell.org
Tue Feb 27 18:05:38 PST 2007
Lists are mutable.
Build your chain of strings in a list, then join using the (string)
member function of the delimiter.
(avoid the old style string.join() -- why: see Bob's old post/link below)
- Horst
>>> tmpList = []
>>> if 1==1 : tmpList.append('1 is 1')
...
>>> if 1==2 : tmpList.append('1 is not 2 --not recorded')
...
>>> if 2==2 : tmpList.append('2 is 2 --recorded')
...
>>> tmpList.append(' etc... ')
>>> commaString = ', '.join(tmpList)
>>> asLines = '\n'.join(tmpList)
>>> commaString
'1 is 1, 2 is 2 --recorded, etc... '
>>> asLines
'1 is 1\n2 is 2 --recorded\n etc... '
>>> print asLines
1 is 1
2 is 2 --recorded
etc...
>>>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Date: Fri, 31 Mar 2006 08:10:24 -0800
From: Bob Miller <kbob at jogger-egg.com>
Subject: [Python] Python idioms and efficiency
I found this on the 'Net. It's a collection of idioms for our favorite
scripting language. Includes some cool techniques.
http://jaynes.colorado.edu/PythonIdioms.html
--
Bob Miller K<bob>
===========================================================
> Date: Tue, 27 Feb 2007 15:39:33 -0800
> From: Rob Hudson <rob at euglug.net>
> Subject: [Python] Python and concatenating strings
>
> I'm working on some code and I'm doing a lot of this:
>
> content = ''
> if blah:
> content += 'something'
> if blah2:
> content += 'something else'
>
> There's lots of that. Is there a faster way to build a string?
>
...
More information about the Python
mailing list