简体   繁体   English

引用第一个字符时,IndexError字符串索引超出范围

[英]IndexError string index out of range when referencing first character

Here is my code (currently): 这是我的代码(当前):

conn = sqlite3.connect(db)
conn.text_factory = str  #bugger 8-bit bytestrings
cur = conn.cursor()

reader = csv.reader(open(csvfile, "rU"), delimiter = '\t')
for Number, Name, Message, Datetime, Type in reader:

# populate subscriber table
if str(Number)[0] == '1': # errors on this line
  tmpNumber = str(Number)[1:]
  Number = int(tmpNumber)
cur.execute('INSERT OR IGNORE INTO subscriber (name, phone_number) VALUES (?,?)', (Name, Number))

cur.close()
conn.close()

It returns this error on the line commented to indicate where the error lies: 它在注释行上返回此错误以指示错误所在:

IndexError: string index out of range

All of the numbers have values, but if the phone number starts with a 1 I want to remove the 1 before inserting it into the database. 所有数字都有值,但是如果电话号码以1开头,我想在将1插入数据库之前将其删除。 Why won't this work? 为什么不起作用? I've converted it to a string before trying to reference the first character, so I don't understand why this isn't working. 在尝试引用第一个字符之前,我已经将其转换为字符串,所以我不明白为什么它不起作用。

Seems like you are getting an empty string. 好像您正在获取一个空字符串。 Try replacing your if statement with the following and see if it works. 尝试将if语句替换为以下内容,看看是否可行。

if str(Number).startswith('1'):

(Edited to reflect @kindall 's suggestion of using startswith instead of slicing [:1] ). (已编辑,以反映@kindall的使用startswith而不是切片[:1] )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM