我正在尝试根据由不同分隔符分隔的文件构建字典。例如,我通过以下方式构建文件即时读取,我需要将该行作为变量用于演示目的
g = "ENGL 1301,preprofessional,MATH 2413,"
if ","and "," in g :
print "yay"
if "," and "," and "," in g:
print "nay"
该文件可以有多个逗号,这意味着不同的东西,所以我试图在行中的逗号数量之间进行区分。我希望上面的程序只打印“nay”,因为字符串中有3个逗号,而不是2.我怎么能完成这个,因为上面的程序失败并打印了“yay”和“nay”
答案 0 :(得分:1)
使用str.count
:
g = "ENGL 1301,preprofessional,MATH 2413,"
commas = g.count(",") # I put this up here so it isn't called multiple times
if commas == 2:
print "yay"
elif commas == 3: # I used `elif` here since `commas` cannot equal 2 and 3
print "nay"
此外,您当前的代码不起作用,因为非空字符串在Python中评估为True
。所以,这个:
if "," and "," in g :
print "yay"
if "," and "," and "," in g:
print "nay"
变成这样:
if True and ("," in g):
print "yay"
if True and True and ("," in g):
print "nay"
正如您所猜测的那样,每个if语句都将始终传递。