简体   繁体   中英

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 (eg ş -> 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'))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM