Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whitespace in a string (python)

Tags:

python

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!!!")
like image 240
Digi_B Avatar asked Nov 18 '14 05:11

Digi_B


3 Answers

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..

like image 54
doniyor Avatar answered Oct 13 '22 17:10

doniyor


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.

like image 42
Nilesh Avatar answered Oct 13 '22 19:10

Nilesh


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
like image 23
Duke Avatar answered Oct 13 '22 19:10

Duke