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!!!")
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..
'B'.split() == 'B '.split() If 'B ' should be considered to have a space, this solution is wrong.\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 newlineYou 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.
isspace does not return true for None or '' . The equivalent of IsNullOrWhiteSpace in .NET would be not s or s.isspace()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
True in ... is equal to any(...).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).any() will return on the first occurence of something evaluating to True! So it does not create the full list first.any(), considering the efficiency improvement mentioned above.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
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'
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!!!")
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.
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)
user = B Bwill be SyntaxError, invalid syntaxisspacefunction only returnsTruefor strings that contain nothing but whitespace.if user.find(' ') >=0 :