[英]string index out of range? - python
im buliding a chat and i'm keep getting the next error: 即时通讯聊天,我不断收到下一个错误:
Traceback (most recent call last):
File "C:/Users/ronen/Documents/CyberLink/tryccc.py", line 651, in <module>
main()
File "C:/Users/ronen/Documents/CyberLink/tryccc.py", line 630, in main
print_message(data_from_server, len(temp_message), username)
File "C:/Users/ronen/Documents/CyberLink/tryccc.py", line 265, in print_message
temp_l = data[0]
IndexError: string index out of range
i am trying to get the first char of the data string and convert it into int but i get this error the problem is in the first line of the code 我正在尝试获取数据字符串的第一个字符并将其转换为int,但是我收到此错误,问题出在代码的第一行
def print_message(d_temp, line_length, this_username):
temp_l = d_temp[0] #the problematic line
len_username = int(temp_l)
username_sender = d_temp[1:(len_username + 1)]
message_sent = d_temp[(len_username + 1): -4]
hour_time = d_temp[-4: -2]
min_time = d_temp[-2:]
printed_message = "\r" + hour_time + ":" + min_time + " " + username_sender + " : " + message_sent
print printed_message, # Prints this message on top of what perhaps this client started writing.
# if this client started typing message
complete_line_with_space(len(printed_message), line_length)
data- the data (string) from the server data-来自服务器的数据(字符串)
line_length - the length of the temp massage line_length-临时按摩的时间
this_username - the client's username this_username-客户端的用户名
thank you to all the helpers 谢谢所有的帮手
empty d_temp
will give this error. 空
d_temp
将给出此错误。 This might be the reason: 这可能是原因:
>>> d_temp = ""
>>> d_temp[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
This happens because print_message
is executed with an empty string as first parameter 发生这种情况是因为以空字符串作为第一个参数执行了
print_message
print_message("",...)
This means the problem is somewhere else in your code. 这意味着问题出在代码的其他地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.