FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!

Python: Changing a string (Assignment)




In "Python: Sequences" I said:
Quote:
A string is a list of characters, like "Hello World!". A list is simply a list of any sort of data element, in many other programming languages known as array. A tuple is like a list, but not changeable.

What I forgot to mention here is: a string is not changeable as well.

Thus, assume you have a string "Hello World." What if you want to change the last character of this string to "!" to get "Hello World!" ? How would you do this ? Or as a more practical example assume you have a string "/tmp/somedir/" and you want to remove the last slash. How would you achieve this ?

Something like this won't work in Python:

Code:
>>> str = "Hello World."
>>> str[-1] = "!"

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    str[-1] = "!"
TypeError: 'str' object does not support item assignment
>>>


Anyone any idea ?



2 blog comments below

I guess you could do something like this
Code:
str = str[:-1] + '!'


Not sure if there are better ways.
Peterssidan on Mon Jul 09, 2012 6:37 pm
Applause Peterssidan, you are perfectly right.
We can verify this by using my Python Expression Evaluator and typing in this expression:

Code:
"Hello World."[:-1]+"!"
amagard on Tue Jul 10, 2012 3:11 pm



FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.