【问题标题】:string index out of range? - python字符串索引超出范围? - Python
【发布时间】:2019-12-24 16:23:54
【问题描述】:

我正在建立一个聊天,我不断收到下一个错误:

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

我正在尝试获取数据字符串的第一个字符并将其转换为 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- 来自服务器的数据(字符串)

line_length - 临时按摩的长度

this_username - 客户的用户名

感谢所有的帮助

【问题讨论】:

  • 可能d_temp 为空..
  • 如果d_temp的长度为零,函数应该怎么做?如果您在想,“那不应该发生”,您是否 100% 确定它永远不会发生?
  • 您的错误与代码不匹配

标签: python string int


【解决方案1】:

发生这种情况是因为print_message 使用空字符串作为第一个参数执行

print_message("",...)

这意味着问题出在代码的其他地方。

【讨论】:

    【解决方案2】:

    empty d_temp 将给出此错误。 这可能是原因:

    >>> d_temp = ""
    >>> d_temp[0]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: string index out of range
    

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 2016-08-11
      相关资源
      最近更新 更多