Shadow Sniffer
Shadow Sniffer

Reputation: 3

TypeError: 'str' object does not support item assignment

I have a problem in my python program. In this program, the user enters a string and then the program calls a function to convert from the unicode letter to the closest ASCII symbol (e.g. ş -> s ö -> o etc.) but i get TypeError: 'str' object does not support item assignment

Code:

__author__ = 'neo'
ceviri = {
    'ş':'s','Ş':'S',
    'ğ':'g','Ğ':'G',
    'ı':'i','İ':'I',
    'ü':'u','Ü':'U',
    'ö':'o','Ö':'O'
}
def karakterDegistir(x):
   p = x[:]
   y = sorted(ceviri.keys())
   u = 0
   while u < len(y):
      if p[u] in y:
         p[u] = ceviri[p[u]]
      u = u + 1
   return p
print(karakterDegistir('şeker'))

Upvotes: 0

Views: 2747

Answers (1)

Foon
Foon

Reputation: 6458

In addition to Barmar's comment about python not allowing you to modify strings in place, you're iterating through your copy of the input array, but you're going up to the length of y (your list of keys), not the length of p.

A much more pythonic way would be return ''.join([ceviri.get(c,c) for c in x])

(Edit: thanks Dair), and since I'm editing: To clarify: this goes through each letter in x, and if that letter is in your ceviri dictionary, return the value, otherwise use the original letter. This creates a list of letters' ''.join combines all the letters into a string.

Upvotes: 1

Related Questions