So, I just started with python and have learned how to fix some issues but I got stuck with this one and what I have searched, doesn't help me.
This is my test.py
file: http://pastebin.com/TzASyCxm where I work with mysql and output some data to an LCD screen.
Right now, executing the code in my script returns the following error:
self.ip[host] = socket.gethostbyname(host)
TypeError: 'str' object does not support item assignment
I'm trying to do like a simple, in php:
$data = array();
$test = 'level1';
$data[$test] = 'alex';
As in PHP, where you need to initialize the variable $data
with an empty array array()
, so as to index and assign elements to it, in similar ways, you need to assign a dictionary to self.ip
to subsequently index and assign values.
The ways you can do it varies with requirement, but we generally stick to one of the two formats
self.ip = dict()
self.ip = {}
Note
Python Error Messages are self explanatory and you can easily identify the Issue from it
TypeError: 'str' object does not support item assignment
It means self.ip
is a string object, and in Python, String Objects are immutable and cannot be indexed unlike C/C++. So likely, you may have initialized this variable somewhere prior to the failure with a string.
As the error states, self.ip
is a string, and you can't assign to elements within a string.
Presumably you meant to initialize it to a dictionary: self.ip = {}