What is the most pythonic way to build up large strings?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Feb 8 12:06:24 CET 2014


On Sat, 08 Feb 2014 01:56:46 -0800, cstrutton11 wrote:

> On Saturday, February 8, 2014 3:13:54 AM UTC-5, Asaf Las wrote:
>> note, due to strings are immutable - for every line in sum operation
>> above you produce new object and throw out older one. you can write
>> one string spanned at multiple lines in very clear form.
>> 
> I get what your saying here about immutable strings.  Is there anyway
> efficiently build large strings with lots of conditional inclusions,
> repetative sections built dynamically by looping (see the field section
> above)etc. 

Yes. Build up all the substrings individually, storing them in a list. 
Then, when you are ready to actually use the string, assemble it in one 
go.

substrings = []
for x in whatever():
    if condition():
        substrings.append("something")

process("".join(substrings))


> Is there a mutable string class?

No. Well, actually there is, but it's a toy, and operates under the hood 
by creating new immutable strings, so there's no point using it. It may 
even have been removed from more recent versions of Python.



-- 
Steven



More information about the Python-list mailing list