关闭
douwen0612 2013-01-21 04:43
浏览 78
已采纳

开始使用python问题

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';
  • 写回答

2条回答 默认 最新

  • douzhe3516 2013-01-21 04:51
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部