Error Occurs: Replace a character in a String
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sun Apr 11 01:59:15 EDT 2010
On Sat, 10 Apr 2010 22:01:51 -0700, Jimbo wrote:
> Hello, I am getting an error in my python script when I try to change a
> character in a string. [b]But I dont know why or what to do to fix
> it?[/b]
>
> I have commented in my code where the error occurs
Generally speaking, posting the actual error (not retyping it from
memory, or summarising it, or eluding to something vaguely similar) is
recommended. In this case though, your error is simple enough that you
can get away without the full traceback:
> temp_buf[hit] = '~'
> # Error: 'str' object does not support item assignment
The error is exactly what it says: strings don't support item assignment.
Try this in an interactive session:
>>> s = 'abcd'
>>> s[1] = 'B'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Just as it says: you can't assign to individual string items (characters).
This is because strings in Python are immutable -- once created, you
can't modify them. There are all sorts of reasons for this, which I won't
go into, but the consequence is that anytime you want to modify a string
you need to create a new one:
>>> s = s[0] + 'B' + s[2:]
>>> s
'aBcd'
But don't do the above! String concatenation is okay if you only do it
once or twice, but if you're doing a lot of it, your code will be
sloooooow. Best to avoid it whenever possible.
The best way to replace substrings is, not surprisingly, to use the
replace() method:
>>> print s.replace('B', '~')
a~cd
Or break the string up into a list of words:
words = mystring.split()
or a list of characters:
chars = list(mystring)
and operate on the list. Lists, unlike strings, are mutable and so you
can assign to items.
But I see you're trying to manually parse HTML. Have you considered using
the HTML parser that comes with Python?
--
Steven
More information about the Python-list
mailing list