如果条件不返回true

时间:2015-04-02 16:25:38

标签: python

string_list = ['[pool]\n', 'pool_name\n', 'node_name ip_address port\n', 'node_name ip_address port\n', 'node_name ip_address port\n', '[/pool]\n', '[pool]\n', 'pool_name\n', 'node_name ip_address port\n', 'node_name ip_address port\n', 'node_name ip_address port\n', '[/pool]\n']
for i in range(len(string_list)):
    print string_list[i]
    if string_list[i] == 'pool_name':
        print "here"

此代码中缺少的内容。 if条件不返回true。

6 个答案:

答案 0 :(得分:2)

试试这个

if string_list[i].strip() == 'pool_name':

由于

>>>>"pool_name\n".strip() # this will strip out \n, \r, \t, " ",
"pool_name"

OR

if string_list[i] == 'pool_name\n':

答案 1 :(得分:2)

您的陈述中缺少\n

列表中的所有字符串最后都有\n

for i in range(len(string_list)):
    print string_list[i]
    if string_list[i] == 'pool_name\n':   #Missing here
        print "here"

更改声明后的输出

[pool]

pool_name

node_name ip_address port

node_name ip_address port

node_name ip_address port

[/pool]

[pool]

pool_name

node_name ip_address port

node_name ip_address port

node_name ip_address port

[/pool]

答案 2 :(得分:0)

在您的列表中,值为'pool_name\n',而不是'pool_name'\n字符的差异,换行符)。要么:

if string_list[i] == 'pool_name\n':

或者:

if string_list[i].strip() == 'pool_name':

答案 3 :(得分:0)

for i in string_list:
    if i.strip() == 'pool_name':
        print "here"   

这将是一种更加pythonic的方式。

或者只是

if 'pool_name\n' in string_list:
    print "here"

答案 4 :(得分:0)

您的字符串以'\n'结尾,您不会检查:

for i in range(len(string_list)):
    print string_list[i]
    if string_list[i] == 'pool_name\n':
        print "here"

或者,strip要移除'\n'的字符串,然后继续检查您的身份:

for i in range(len(string_list)):
    print string_list[i]
    if string_list[i].strip() == 'pool_name':
        print "here"

因此:

>>> foo()
[pool]

pool_name

here
node_name ip_address port

node_name ip_address port

node_name ip_address port

[/pool]

[pool]

pool_name

here
node_name ip_address port

node_name ip_address port

node_name ip_address port

[/pool]
>>>

答案 5 :(得分:0)

您需要使用strip()功能

清理输入
string_list = ['[pool]\n', 'pool_name\n', 'node_name ip_address port\n', 'node_name ip_address port\n', 'node_name ip_address port\n', '[/pool]\n', '[pool]\n', 'pool_name\n', 'node_name ip_address port\n', 'node_name ip_address port\n', 'node_name ip_address port\n', '[/pool]\n']

string_list =   [i.strip() for i in string_list]

string_list
['[pool]', 'pool_name', 'node_name ip_address port', 'node_name ip_address port', 'node_name ip_address port', '[/pool]', '[pool]', 'pool_name', 'node_name ip_address port', 'node_name ip_address port', 'node_name ip_address port', '[/pool]']

那么你可以做你正在做的事情

for i in range(len(string_list)):
    print string_list[i]
    if string_list[i] == 'pool_name':   
        print "here"