Error Occurs: Replace a character in a String

Patrick Maupin pmaupin at gmail.com
Sun Apr 11 08:08:23 CEST 2010


On Apr 11, 12:01 am, Jimbo <nill... at yahoo.com> 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
>
> [code]
> def format_file(filename):
>
>     HTML_file   = open(filename,'r')
>     HTML_source = HTML_file.read()
>     HTML_file.close()
>
>     x = 0
>
>     # Format all ID's & classes correctly
>     temp_buf        = HTML_source.lower()
>     class_occurence = temp_buf.count('class')
>     ID_occurence    = temp_buf.count('id')
>
>     for n in range(class_occurence):
>         hit = temp_buf.find('class')
>         if not hit==-1:
>             temp_buf[hit] = '~' # Error: 'str' object does not support
> item assignment
>             x = hit+5
>
>             # delete any spaces until we reach a letter or number
>             while x<temp_buf[x]:
>                 if temp_buf[x] == ' ':
>                     tempbuf[x]     = ''
>                     HTML_source[x] = ''
>                 elif temp_buf[x] == '=':
>                     pass
>                 #elif temp_buf[x] == "'" or temp_buf[x] == '"'
> isalpha(temp_buf[x])
>                 else:
>                     break
>                 x += 1
> [/code]

In Python, a string is an immutable (unchangeable) object.

You can convert a string into a list of characters (which is not
immutable:

mylist = list(temp_buf)

and then convert it back:

temp_buf = ''.join(mylist)

but you cannot do item assignments inside the string (and lists don't
have a find method, so you cannot use find on your list).  You can
maintain a parallel list and string if you want (with the same
indices).

Also, not sure what you want to accomplish with this statement:

   while x<temp_buf[x]:

Do you maybe mean something like:

    while x < len(temp_buf):

This whole approach (character by character processing) is pretty
inefficient (which may or may not not matter for your use).  There are
several HTML parsers available for Python, as well.

HTH,
Pat



More information about the Python-list mailing list