简体   繁体   English

当 IF 语句为假时为变量赋值会导致 Python 中的错误

[英]Assigning value to variable when IF statement is false causes error in Python

I'm writing a function in Python that should search a string for a substring, then assign the index of the substring to a variable.我正在用 Python 编写一个函数,它应该在字符串中搜索子字符串,然后将子字符串的索引分配给变量。 And if the substring isn't found, I'd like to assign -1 to the variable to be used as a stop code elsewhere.如果未找到子字符串,我想将 -1 分配给变量以用作其他地方的停止代码。 But I get an error that I don't understand.但我得到一个我不明白的错误。 Here is a simplified version of the code:这是代码的简化版本:

test = "abc"
search_str = "z"
index_search_str = test.index(search_str) if search_str in test else index_search_str = -1

If I run this code, the value of index_search_str should be -1, but instead I get this error (using PyCharm):如果我运行这段代码, index_search_str的值应该是-1,但是我得到了这个错误(使用 PyCharm):

 index_search_str = test.index(search_str) if search_str in test else index_search_str = -1
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

But if I change = -1 to := -1 , it still gives an error.但是,如果我将= -1更改为:= -1 ,它仍然会出错。 What am I missing?我错过了什么?

I think, in using ternary operator, value should be returned.我认为,在使用三元运算符时,应该返回值。

test = "azbc"
search_str = "z"
index_search_str = test.index(search_str) if search_str in test else -1

print(index_search_str)    # print value maybe  "1"

You cannot assign variable in one-line statement您不能在一行语句中分配变量

test = "abc"
search_str = "z"
index_search_str = test.index(search_str) if search_str in test else -1

Your code have syntax errors.您的代码有语法错误。

I think you need something like this:我认为你需要这样的东西:

test = "abc"
search_str = "z"
if search_str in test:
    print("match")
    index_search_str = test.index(search_str)
    print(index_search_str)
else :
    print("not match")
    index_search_str = -1
    print(index_search_str)

"not match" “不匹配”
"-1" “-1”

test = "abc"
search_str = "c"
if search_str in test:
    print("match")
    index_search_str = test.index(search_str)
    print(index_search_str)
else :
    print("not match")
    index_search_str = -1
    print(index_search_str)

match匹配
2 2

Just use str.find instead... it does exactly what you're trying to do by default.只需使用str.find ......它会完全按照您默认的方式执行。

>>> test = "abc"
>>> print(test.find('z'))
-1

>>> print(test.find('b'))
1

Try尝试

index_search_str = test.index(search_str) if search_str in test else -1 index_search_str = test.index(search_str) if search_str in test else -1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM