Home > Software design >  Check if word is contained exactly in a Python string
Check if word is contained exactly in a Python string

Time:11-04

I have this case:

a = "I run away without you"
if "with" in a:
    print("s")
else:
    print("n")

This expression is True. But, I want to print "n", because a has to have exactly "with" and not a substring. How can I do this?

CodePudding user response:

Maybe you mean this:

"with" - True
"without" - False
"with xxx" - True

you can try: if "with" in a.split(" "):

CodePudding user response:

I am not sure I understand the problem you are having but if what you are trying to do is check whether your variable only contains the string "with", then use == instead of in

  • Related