Check if space is in a string

前端 未结 5 2256
执笔经年
执笔经年 2021-02-11 14:08
\' \' 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

相关标签:
5条回答
  • 2021-02-11 14:37

    Write if " " in word: instead of if " " in word == True:.

    Explanation:

    • In Python, for example a < b < c is equivalent to (a < b) and (b < c).
    • The same holds for any chain of comparison operators, which include in!
    • Therefore ' ' in w == True is equivalent to (' ' in w) and (w == True) which is not what you want.
    0 讨论(0)
  • 2021-02-11 14:37

    You can say word.strip(" ") to remove any leading/trailing spaces from the string - you should do that before your if statement. That way if someone enters input such as " test " your program will still work.

    That said, if " " in word: will determine if a string contains any spaces. If that does not working, can you please provide more information?

    0 讨论(0)
  • 2021-02-11 14:48

    There are a lot of ways to do that :

    t = s.split(" ")
    if len(t) > 1:
      print "several tokens"
    

    To be sure it matches every kind of space, you can use re module :

    import re
    if re.search(r"\s", your_string):
      print "several words"
    
    0 讨论(0)
  • == 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
    
    0 讨论(0)
  • 2021-02-11 14:54

    You can try this, and if it will find any space it will return the position where the first space is.

    if mystring.find(' ') != -1:
        print True
    else:
        print False
    
    0 讨论(0)
提交回复
热议问题