Search code examples
pythonstringattributes

Type 'str' doesn't have expected attribute '__setitem__' in Python


Why do I get "Type 'str' doesn't have expected attribute '__setitem__'" when I call my static class method?

@staticmethod
def replace_region_decimal_sign(to_convert):
    to_convert[to_convert.index(',')] = '.'  # Replace comma ("region" decimal sign) with a dot
    return to_convert

enter image description here

if __name__ == "__main__":
    print(Calculator.replace_region_decimal_sign("1,23"))

enter image description here


Solution

  • Strings are inmutable in Python, therefore they can't be changed and don't implement __setitem__.

    Try something like:

    i = to_convert.index(',')
    to_convert = to_convert[:i] + '.' + to_convert[i+1:]
    

    This generates a new string.