18

Why do I always get YES!!!? I need to return NO!!! if the string contain a whitespace (newline, tap, space)

user = "B B"

if user.isspace():
    print("NO!!!")
else:
    print("YES!!!")
4
  • user = B B will be SyntaxError, invalid syntax Commented Nov 18, 2014 at 5:32
  • 5
    The isspace function only returns True for strings that contain nothing but whitespace. Commented Nov 18, 2014 at 5:33
  • 1
    Then how can I check if there is a space in a string? Commented Nov 18, 2014 at 5:35
  • @Digi_B use if user.find(' ') >=0 : Commented Dec 19, 2021 at 17:35

10 Answers 10

12
def tt(w): 
    if ' ' in w: 
       print 'space' 
    else: 
       print 'no space' 

>>   tt('b ')
>> space
>>  tt('b b')
>> space
>>  tt('bb')
>> no space

I am in train, sorry for not explaining.. cannot type much..

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. But When I run this with "B B" I get "theres space" just as I want. However, when I run "B " I get no space. Why?
Try 'B'.split() == 'B '.split() If 'B ' should be considered to have a space, this solution is wrong.
@gamedesigner edited the answer. Now it works for both cases.
Does not work for a \t or \n or any whitespace character other than ASCII 0x20 (a normal space bar character). The OP stated any whitespace, including a tab or newline
10

You are using isspace which says

str.isspace()

Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.

For 8-bit strings, this method is locale-dependent.

2 Comments

While a totally valid explanation, this does not show how to fix.
Please note: isspace does not return true for None or '' . The equivalent of IsNullOrWhiteSpace in .NET would be not s or s.isspace()
8

Here is a neat method that illustrates the flexibility of list comprehensions. It is a helper method that checks to see if a given string contains any whitespace.

Code:

import string
def contains_whitespace(s):
    return True in [c in s for c in string.whitespace]

Example:

>>> contains_whitespace("BB")
False
>>> contains_whitespace("B B")
True

This can, of course, be extended to check if any string contains an element in any set (rather than just whitespace). The previous solution is a neat, short solution, but some may argue it is hard to read and less Pythonic than something like:

def contains_whitespace(s):
    for c in s:
        if c in string.whitespace:
            return True
    return False

4 Comments

True in ... is equal to any(...).
To expand on ArtOfWarfare's comment, the more elegant solution would perhaps be to use a generator expression with any(), for example: return any(c in s for c in string.whitespace). A quick benchmark on my box shows that any() runs slightly faster under CPython 3.6 than the list comprehension (you mileage may vary, depending on the typical format of the string you expect).
Yes. any() will return on the first occurence of something evaluating to True! So it does not create the full list first.
This is the best answer, considering whitespace is more than just spaces. Although it should be updated to use any(), considering the efficiency improvement mentioned above.
3

Since you are looking for more than just a simple ' ' where you could use ' ' in tgt you can use any:

for s in ('B ', 'B B', 'B\nB', 'BB'):
    print repr(s), any(c.isspace() for c in s)

Prints:

'B ' True
'B B' True
'B\nB' True
'BB' False

Comments

2
user = 'B B'
for x in user:
    if x.isspace():
        print("no")
    else:print("yes")

you need to loop over it to check for all element, but the above code will not work as you expect.

use a helper function:

def space(text):
    if ' ' in text:
        return True
    else: return False

demo:

>>> ' ' in 'B B'
True
>>> ' ' in 'BB'
False

use in to check

if you want to use isspace:

def space(text):
    for x in text:
        if x.isspace():
            return True
    return False

Instead of returning True or False you can return Desired string too:

>>> def space(text):
...     if ' ' in text:
...         return " yes Spaces"
...     else: return " No Spaces"
... 
>>> space('B B')
' yes Spaces'
>>> space('BB')
' No Spaces'

2 Comments

This would display the result for each character. I only want to display "no" if there is a whitespace and "yes" if there is not.
yep , i am making a helper to make it OP better to understand
2

There are already good answers to your question. Here is a way to get total number of spaces (or any other char) in string

>>> "I contain 3 spaces".count(" ")
3
>>> "Nospaces".count(" ")
0

Comments

1

You can use str.split to check if a string contains spaces:

>>> ''.split()
[]
>>> '  '.split()
[]
>>> 'BB'.split()
['BB']
>>> ' B '.split()
['B']
>>> 'B B'.split()
['B', 'B']

So you can check as

def hasspace(x):
    if x:
        s = x.split()
        return len(s) == 1 and x == s[0]
    return False

If you are only trying to check for whole words in the string (i.e., you are not worried about surrounding spaces that could be removed by x.strip()), the condition x == s[0] is no longer necessary. The check becomes a single statement:

def hasspace(x):
    return x and len(x.split()) == 1

Now you can do

if hasspace(user):
    print("NO!!!")
else:
    print("YES!!!")

Comments

1

You can loop through the string and check for whitespaces.

make a variable 'is_there_whitespace'

as its value, give it the length of whitespce found

If its greater than 0 boom you got white space.

user = "B B"

is_there_whitespace = len([True for x in user if x.isspace()])

print(f"Is there white space? {is_there_whitespace>0}.")
print(f"Amount of white spaces found:{is_there_whitespace}")
> Is there white space? True.
> Amount of white space found:1.

Comments

0
In [1]: a<br>
Out[1]: ' b\t\n'

In [2]: (' ' in a)or('\t' in a)or('\n' in a)<br>
Out[2]: True

Comments

0

To efficiently check if there is any whitespace character in a given string:

any(map(str.isspace, mystr))

Also, as previously answered by dawg, another way to write it is:

any(char.isspace() for char in mystr)

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.