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..
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With