[Tutor] working with strings in python3

Marc Tompkins marc.tompkins at gmail.com
Tue Apr 19 04:50:02 CEST 2011


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


> I'm going to go ahead and use this format even though it is deprecated
> and then later when we upgrade it I can fix it.
>
> And there you have your answer.

A list might make sense, but printing a message one word at a time
> doesn't seem to me like much of a time saver.
>

Did you try my example code?  It doesn't "print a message one word at a
time"; any time you print " ".join(message), you get the whole thing.  Put a
\n between the quotes, and you get the whole thing on separate lines.

It's just that it's not stored as a single string, but assembled on-demand.
And you're right - doing this once or twice, or even ten times as in my
example code, doesn't make a huge difference.  But at some point, if you
intend to continue programming, you will run into a situation where your
code needs to do something over and over and over and over... and getting
out of bad habits like string concatenation can make a very noticeable
difference in speed.


> But are CLI apps so rare that this sort of thing just doesn't happen
> anymore?


No, they're not all that rare, and CLI-ness has nothing to do with it.


> This seems like such a basic thing and deprecating it seems
> rather harsh.
>
> Bottom line: Python is not BASIC.  In BASIC, strings aren't immutable, so
in-place string concatenation doesn't carry (much of) a performance
penalty.  In Python, it will make your program unnecessarily slow.  I think
you're under the impression that "deprecation" is a value judgment, or that
"message = message + foo" is deprecated because it looks like BASIC syntax.
Neither is true.

>From the Python wiki:
http://wiki.python.org/moin/PythonSpeed/PerformanceTips#String_Concatenation


We may ask ourselves "why did Guido decide to make strings immutable in the
first place?"; probably the best reason is "so that strings can be used as
keys in a dictionary", but since I'm not Guido - not even Dutch! - I really
can't speak for him.

I'm not really trying to start a flame fest, I'm just trying to
> understand the thought process.  I don't see what I would call a
> legitimate alternative to this type of string usage.
>

Again, that's because you're holding onto the idea of mutable strings.
Accept that they're immutable, but that lists of strings are both mutable
and fast, and the difficulties disappear.

But also: if you want to use concatenation, knock yourself out!  Nobody's
going to condemn you for it.  Except possibly your users.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110418/666f6455/attachment-0001.html>


More information about the Tutor mailing list