[Tutor] working with strings in python3

Marc Tompkins marc.tompkins at gmail.com
Tue Apr 19 03:10:13 CEST 2011


On Mon, Apr 18, 2011 at 5:17 PM, Rance Hall <ranceh at gmail.com> wrote:

> Ok so I know what I am doing is deprecated (or at least poor form) but
> the replacement must be awkward cause I'm not getting it.
>
>
> so this is in a cli based program designed to print status messages to
> the terminal on a linux box.
>
> pseudo code:
>
>
> message = "Bah."
>
> if test:
>   message = message + " Humbug!"
>
> print(message)
>
> end pseudo code
>
>
> I'm sure this is not the way we are supposed to augment strings like this.
>
> maybe there is string.append() method or something I should be using
> instead?
>
> In my case the optional extra parts are always at the end of the
>
>> current value of the string.
>>
>
>
The reason it's deprecated is because it's SLOW - since strings are
immutable, there's a lot of extra copying going on behind the scenes.  If
this code were inside a loop, being run lots and lots of times, this would
quickly become one of the bottlenecks of your program.  However, in the
example you've given, I'm not sure it would make an important difference -
as slow as string concatenation is, it's still a heck of a lot faster than
the human operator!

If you just want to have a status update for your user - like a progress bar
- you could simply print one string at a time and not store the result.
(i.e. if you just want to display a line of dots to indicate activity, you
don't need to store the full number of dots - just print one at a time -
without newlines - and forget about it.)

If, on the other hand, you always want to have access to the full string AND
you want to print it along the way, then try a list.  Lists are awesome!

message = ['Bah'] # message is a list, which currently contains one item:
> 'Bah'
> for x in range(10):
>     message.append(str(x))  # append a string ('0', '1', etc.) to the list
>     print " ".join(message)  # print the contents of the list, separated by
> spaces
>

That's if you want to do this in a loop.  If you have a set number of items
to display, then string formatting is your friend:

message = 'The %s in %s stays mainly in the %s' % ('rain', 'Spain', 'plain')
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110418/5545cf28/attachment.html>


More information about the Tutor mailing list