Python 3.x 如何使用变量剥离()和拆分()?

Python 3.x 如何使用变量剥离()和拆分()?,python-3.x,variables,split,null,strip,Python 3.x,Variables,Split,Null,Strip,Strip和split都接受字符串(例如)split('\t'),但是由于某种原因,由变量“stripped_character”和“delimiter”存储的字符串不能正常工作(我认为它们返回的是空字段)。如果我手动输入一些值,这段代码可以工作(例如)linefromfile=line.strip('\n').split('\t') 回溯错误如下所示: 回溯(最近一次呼叫最后一次): 文件“C:/Users/Hezekiah/PycharmProjects/Great-Courses-Pyth

Strip和split都接受字符串(例如)split('\t'),但是由于某种原因,由变量“stripped_character”和“delimiter”存储的字符串不能正常工作(我认为它们返回的是空字段)。如果我手动输入一些值,这段代码可以工作(例如)linefromfile=line.strip('\n').split('\t')

回溯错误如下所示: 回溯(最近一次呼叫最后一次): 文件“C:/Users/Hezekiah/PycharmProjects/Great-Courses-Python/testing.py”, 第14行,在 如果int(tuple1[1][:4])==qdate:
索引器错误:元组索引超出范围

您实际为这些字符串键入了什么?如果您要为分隔符键入
\t
,这只是一个反斜杠,后跟一个“t”-将其解释为制表符的转义序列适用于字符串文字,而不是来自任意其他来源的字符串。我键入\n表示剥离字符,\t表示分隔符。你能想出一种方法把它转换成字符串文字吗?试试
input(“…”).encode().decode(“unicode转义”)
来应用相同的转义处理。我的问题现在已经完全解决了。如果jasonharper留下他的评论作为答案,我会把它标记为正确的。你到底在为这些字符串输入什么?如果您要为分隔符键入
\t
,这只是一个反斜杠,后跟一个“t”-将其解释为制表符的转义序列适用于字符串文字,而不是来自任意其他来源的字符串。我键入\n表示剥离字符,\t表示分隔符。你能想出一种方法把它转换成字符串文字吗?试试
input(“…”).encode().decode(“unicode转义”)
来应用相同的转义处理。我的问题现在已经完全解决了。如果贾森·哈珀留下他的评论作为回答,我会认为这是正确的。
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()