Check if space is in a string

前端 未结 4 963
醉酒成梦
醉酒成梦 2021-02-11 14:21
\' \' in word == True

I\'m writing a program that checks whether the string is a single word. Why doesn\'t this work and is there any better way to che

4条回答
  •  心在旅途
    2021-02-11 14:55

    == takes precedence over in, so you're actually testing word == True.

    >>> w = 'ab c'
    >>> ' ' in w == True
    1: False
    >>> (' ' in w) == True
    2: True
    

    But you don't need == True at all. if requires [something that evalutes to True or False] and ' ' in word will evalute to true or false. So, if ' ' in word: ... is just fine:

    >>> ' ' in w
    3: True
    

提交回复
热议问题