2

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?

2
  • 6
    You got your ternary operator wrong. the assignment only happens at the start, not in the "else". Corrected version: index_search_str = test.index(search_str) if search_str in test else -1 Commented Jul 17, 2022 at 0:56
  • The real question is, why are you not just using index_search_str = test.find(search_str)? Commented Jul 17, 2022 at 2:45

5 Answers 5

3

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"
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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

Comments

1

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

Comments

0

Try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.