[英]ELSE Statement for CSV file not working
I'm trying to fit in an ELSE
statement for a variable within a CSV
File.我正在尝试为
CSV
文件中的变量添加ELSE
语句。
CSV File: CSV 文件:
abcd, qwerty, aoo9 afjd, wijfs, aaaa 12as, 54as, oozz
I have attempted the following:我尝试了以下方法:
string1 = raw_input('User input: ')
with open('FILE.csv', "rb") as csvfile:
z = csv.reader(csvfile, delimiter=',')
for row in z:
if string1 in row[1]:
print 'A'
else:
print 'B'
sys.exit()
However, regardless of whether the user's input is in row[1]
or not, it will still print ' B
'.但是,无论用户的输入是否在
row[1]
,它仍然会打印 ' B
'。
I expect that if the user inputs qwerty
, wijfs
, or 54as
as string1 which all lie in row[1]
, it will print ' A
', however if the user inputs something for string1 does is not in row[1]
, it will print ' B
'我希望如果用户输入
qwerty
、 wijfs
或54as
作为 string1 ,它们都位于row[1]
,它将打印“ A
”,但是如果用户输入 string1 的某些内容不在row[1]
,它将打印打印“ B
”
I have also tried:我也试过:
elif variable not in row [1]: #...
But that doesn't work either.但这也行不通。
Thanks.谢谢。
Your CSV file contains spaces.您的 CSV 文件包含空格。 Your program will behave as expected if you input
" querty"
instead of "querty"
.如果您输入
" querty"
而不是"querty"
您的程序将按预期运行。
You can modify the CSV file or use the strip
function to remove leading and trailing whitespace of row[1]
.您可以修改 CSV 文件或使用
strip
函数删除row[1]
前导和尾随空格。
Or use the skipinitialspace
parameter of the csv.reader
.或者使用
skipinitialspace
的参数csv.reader
。 ;) ;)
Clearly, either variable
or row[1]
does not contain what you think it contains.显然,
variable
或row[1]
不包含您认为它包含的内容。 Add a print statement as follows:添加打印语句如下:
for row in z:
print '<{}> ?= <{}>'.format(variable, row[1]) # add this line.
if variable in row[1]:
to see what's in those two variables (including leading or trailing white space).查看这两个变量中的内容(包括前导或尾随空格)。 Most likely, they will not contain what you think they contain.
最有可能的是,它们不会包含您认为它们包含的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.