1 Replies - 725 Views - Last Post: 10 April 2010 - 10:15 PM Rate Topic: -----

#1 gretty  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 123
  • Joined: 25-May 09

Error Occurs: Replace a character in a String

Posted 10 April 2010 - 10:01 PM

Hello, I am getting an error in my python script when I try to change a character in a string. But I dont know why or what to do to fix it?

I have commented in my code where the error occurs

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



Is This A Good Question/Topic? 0
  • +

Replies To: Error Occurs: Replace a character in a String

#2 erik.price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 485
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Re: Error Occurs: Replace a character in a String

Posted 10 April 2010 - 10:15 PM

In Python, strings are immutable.

From the Python docs:

Quote

Unlike a C string, Python strings cannot be changed. Assigning to an indexed position in the string results in an error:


You can however create a new string. Here's an example using slices:
>>> a = "0123456789"
>>> ind = 5
>>> a = a[0:ind] + '~' + a[ind+1:]
>>> a
'01234~6789'


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1