Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #3525
| Subject | Re: [Tutor] working with strings in python3 |
|---|---|
| From | Westley MartÃnez <anikom15@gmail.com> |
| References | <BANLkTik3h6PP=3zenu+Deo+MAMN3jUTtxg@mail.gmail.com> <mailman.531.1303173290.9059.python-list@python.org> <4dacf094$0$29984$c3e8da3$5496439d@news.astraweb.com> |
| Date | 2011-04-18 20:26 -0700 |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.539.1303183591.9059.python-list@python.org> (permalink) |
On Tue, 2011-04-19 at 02:16 +0000, Steven D'Aprano wrote:
> On Tue, 19 Apr 2011 10:34:27 +1000, James Mills wrote:
>
> > Normally it's considered bad practise to concatenate strings.
>
> *Repeatedly*.
>
> There's nothing wrong with concatenating (say) two or three strings.
> What's a bad idea is something like:
>
>
> s = ''
> while condition:
> s += "append stuff to end"
>
> Even worse:
>
> s = ''
> while condition:
> s = "insert stuff at beginning" + s
>
> because that defeats the runtime optimization (CPython only!) that
> *sometimes* can alleviate the badness of repeated string concatenation.
>
> See Joel on Software for more:
>
> http://www.joelonsoftware.com/articles/fog0000000319.html
>
> But a single concatenation is more or less equally efficient as string
> formatting operations (and probably more efficient, because you don't
> have the overheard of parsing the format mini-language).
>
> For repeated concatenation, the usual idiom is to collect all the
> substrings in a list, then join them all at once at the end:
>
> pieces = []
> while condition:
> pieces.append('append stuff at end')
> s = ''.join(pieces)
>
>
>
>
> --
> Steven
Thanks Steven, I was about to ask for an efficient way to concatenate an
arbitrary amount of strings.
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar
Re: [Tutor] working with strings in python3 James Mills <prologic@shortcircuit.net.au> - 2011-04-19 10:34 +1000
Re: [Tutor] working with strings in python3 Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-04-19 02:16 +0000
Re: [Tutor] working with strings in python3 Chris Angelico <rosuav@gmail.com> - 2011-04-19 13:22 +1000
Re: [Tutor] working with strings in python3 Westley MartÃnez <anikom15@gmail.com> - 2011-04-18 20:26 -0700
csiph-web