python - 字符串索引超出范围? - Python

标签 python string int

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

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

关于python - 字符串索引超出范围? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57556907/

相关文章:

python - 如何根据合并列拆分为多行

python - 使用 Pathlib 通配绝对路径

python - 如何在 python 中将十六进制转换为 ascii 十六进制字符串?

c++ - 声明的 int 具有随机起始值

python - 连接中的 ModuleNotFoundError

javascript - 将字符串拆分为多个文本输入

java - String.format() 在参数为空字符串时添加 2 个空格

java - 如何用空格左填充整数?

C 写入字符串(询问具体功能)

python - 从 azure 函数访问 keyvault secret 失败