[Tutor] working with strings in python3
Steve Willoughby
steve at alchemy.com
Tue Apr 19 02:33:14 CEST 2011
On 18-Apr-11 17:17, Rance Hall wrote:
> if test:
> message = message + " Humbug!"
> 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?
Nope, strings are immutable so once they are instantiated they cannot be
changed (or lots of things like dictionary keys would break).
So you want to create a new string value by taking the current value of
message, plus a new value, and assigning that back to the name "message"
as a new string object:
message = message + " Humbug!"
Although that can be more conveniently written as
message += " Humbug!"
There are other approaches, like building a list of strings and later
joining them, etc., but that depends on your application as to what
approach makes most sense for you.
message.append() is impossible because that would be altering the string
object named by "message" in-place, which is disallowed for strings.
--
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
More information about the Tutor
mailing list