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. And if the substring isn't found, I'd like to assign -1 to the variable to be used as a stop code elsewhere. 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 = 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. 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"
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
Just use str.find
instead... it does exactly what you're trying to do by default.
>>> 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.