[Tutor] capitalize() but only first letter
Jeff Shannon
jeff@ccvcorp.com
Thu Feb 6 12:09:01 2003
Erik Price wrote:
> Unless it is because every time a concatenation is performed, then a
> *new* string is created, so you end up with (x + (x - 1)x) strings
> (because as the parser moves to the next string, it creates a new
> string to represent the strings concatted thus far, then again with
> the *next* string, etc).
This is exactly the case. When you execute a line of code like, say,
greeting = "Hello" + " " + "world" + "!"
You end up building and then throwing away several strings. First the
parser will see "Hello + " " and perform that addition, creating a new
string "Hello ". Next it adds *that* string to "world", creating the
string "Hello world", and throwing away the just-created string "Hello
". Then it adds "!", creating the complete string "Hello world!", and
throwing away the previous "Hello world". Each addition beyond the
first results in a "wasted" string.
By contrast, look at the following almost-equivalent bits of code:
words = ["Hello", " ", "world", "!"]
greeting = ''.join(words)
greeting = '%s%s%s%s' % ("Hello", " ", "world", "!")
Both of these snippets start with the same source strings as the
addition version. Each of them creates one other object (a list in the
first case, a tuple in the second), but no matter how many more words
are added, there are no other "wasted" objects getting thrown away.
Adding 12 words together results in 10 throwaway strings, but joining
or %-formatting 12 words still results in a single throwaway sequence
object.
As a minor additional (pun not intended) point, I have a personal
preference to avoid using + with strings because eventually, that's
going to lead to code that reads something like "1" + "2", which may
lead to expecting either a result of "12" or "3". (Obviously, the real
result is "12", but if I scanned over that in the middle of a page of
unfamiliar code, I might not see the obvious... especially since, as I
understand it, that same code in Perl *would* yield 3!)
Jeff Shannon
Technician/Programmer
Credit International