Home > Mobile >  How to fix this TypeError?
How to fix this TypeError?

Time:04-21

The error I get: string[x][y] = str(chr(ord(string[x][y]) 32)) TypeError: 'str' object does not support item assignment

I am trying to add 32 to the ascii value of the letter string[x][y] so it is capitalized (if its not already capitalized) How can I capitalize a letter in a string without changing the code I wrote?


def Capitalize():
    file = open("file.txt", "r ")                   #opens the file 
    string = str(file.readlines())                  #safes the content of "file" in string
    string = string.split()                         #splits the string into an array for every word
    for x in range(len(string)):                    #for every "subarray"
        for y in range(len(string[x])):             #for every letter in the "subarray" string[x]
            if y == 0:
                if ord(string[x][y]) < 97:          
                    string[x][y] = str(chr(ord(string[x][y])   32)) #here is the TypeError

´´´


CodePudding user response:

It's because string in python is an immutable type, so when you do

string[x][y] = str(chr(ord(string[x][y])   32))

You're trying to change the value of the string, and it won't work. Instead, you should replace the string with the new value

string[x] = string[x][:y]   str(chr(ord(string[x][y])   32))   string[x][y 1:]

(

Also just in case, in a real scenario you will just want to use this to achieve the same thing :

def Capitalize():
    file = open("file.txt", "r ")                   
    string = str(file.readlines())  
    return string.upper()

)

CodePudding user response:

Maybe you can simplify it:

after you have a list of individual strings:

for one_string in string:
    # get index of current string in list
    current_index = string.index(one_string)
    # get first letter
    first_char = one_string[0]
    # replace first letter in individual string with uppercase (if it's already upper case, nothing will happen)
    one_string = one_string.replace(first_char, first_char.upper())
    # switch string at current index for new string starting with uppercase
    string[current_index] = one_string

# list with capitalised first letters
print(string)
  • Related