首页 > 解决方案 > 如何使用变量剥离()和拆分()?

问题描述

W_A11, 2008-02, Moving average, 59.66666667, 50.92582302, 68.40751031, Injuries, Number, Assault, Validated, Whole pop, All ages, Fatal,
W_A11, 2010-03, Moving average, 60, 51.23477459, 68.76522541, Injuries, Number, Assault, Validated, Whole pop, All ages, Fatal,
W_A11, 2017-04, Moving average, 59, 50.30812505, 67.69187495, Injuries, Number, Assault, Validated, Whole pop, All ages, Fatal

qdate = int(input("please enter 2000, 2010, or 2017"))
infile = open('injury_statistics.txt', "r")
outfilename = input("please enter the name of the file to which you want to 
                     append ex) injury_statistics_datafile.txt ")
outfile = open(outfilename, "a")
stripped_character = input("please enter any character you want stripped 
                            from the data ")
delimiter = input("please enter the delimiter for the file ")
# print(type(stripped_character))
# print(type(delimiter))
# the above two lines prove that stripped_character and delimiter are 
# strings
next(infile)
for line in infile:
    linefromfile = line.strip(stripped_character).split(delimiter)
    tuple1 = tuple(linefromfile)
    if int(tuple1[1][:4]) == qdate:
        outfile.write('\n')
        outfile.write(str(linefromfile))
infile.close()
outfile.close()

剥离和拆分都采用字符串 ex) split('\t'),但由于某种原因,我的变量“stripped_character”和“delimiter”存储的字符串不能正常工作(我认为它们返回空字段)。如果我手动输入一些值,则此代码有效,例如)linefromfile = line.strip('\n').split('\t')。

回溯错误如下所示: Traceback (最近一次调用最后一次): File "C:/Users/Hezekiah/PycharmProjects/Great Courses Python/testing.py", line 14, in if int(tuple1[1][:4] ) == qdate: IndexError: 元组索引超出范围

标签: python-3.xvariablessplitnullstrip

解决方案


推荐阅读