[Tutor] working with strings in python3
Alan Gauld
alan.gauld at btinternet.com
Tue Apr 19 23:47:07 CEST 2011
"Rance Hall" <ranceh at gmail.com> wrote
> Ok so I know what I am doing is deprecated
I'm not aware of string concatenation being deprecated.
Ols string formatting is deprecated in the sense that the new
string format() method will replace it, but I don't even
expect to see that any time soon - too much old code
uses formatting.
> the replacement must be awkward cause I'm not getting it.
There is no replacement but there are alternatives.
But the choice of when to use concatenation or when to
use the other methods is usually a matter of style and,
occasionally, of performance
> message = "Bah."
>
> if test:
> message = message + " Humbug!"
Apart from maybe using += instead of + I see nothing
wrong with this usage.
> print(message)
Although you could have missed it out and gone straight to:
print(message,'Humbug!')
Since print will concatenate it's output for you.
> I'm sure this is not the way we are supposed to augment strings like
> this.
It works fine for me, and I don't recall seeing anything saying
not to do it. It carries a small performance and memory overhead
but thats only a problem in a tight or long loop or if dealing with
enormous strings (say megabyte size)
> maybe there is string.append() method or something I should be using
> instead?
You can use the join method of lists which is faster but less obvious:
" ".join([message,'Humbug!"])
Or you can use string formatting
"{1}{2}".format(message,"Humbug!")
I'm not sure how the format() method compares to join for speed,
the old style formatting seemed about equivalent in my highly
unscientific testing...I haven't tried the new style - I don;t care
that much!.
> In my case the optional extra parts are always at the end of the
> current value of the string.
If you only do that operation "occasionally" then using '+' is OK.
Don't get overly anxious. Readability counts too.
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list