Rafael T
Rafael T

Reputation: 15689

check if a string has only white characters in python

What is the easyest way to check if a String has only white characters, like \r \t \n " "?

Upvotes: 3

Views: 1217

Answers (2)

Toothpick Anemone
Toothpick Anemone

Reputation: 4636

The Desired Behavior

The following contains a description of the desired behavior....


Specific Behavior

INPUT DESCRIPTION OUTPUT
"a b c" Letters and Spaces
mixed together.
False
"abc" Letters Only False
" " Three Spaces True
"" Empty String No Exception is raised.
It undefined whether the return value is True or False
" " One Space True
"\t" Tab-character True
"\r" Carriage Return True
"\n" Line-Feed True
"\v" Vertical Tab True
"\f" form-feed True
"\t\v\t\rn" Mixture of tabs and other white characters True

General Behavior

In ASCII, the whitespace characters are:

  • space ( ' ' )
  • tab ( '\t' )
  • carriage return ( '\r' )
  • newline ( '\n' )
  • vertical tab ( '\v' )
  • formfeed ( '\f' )
def is_pure_white(itext:str) -> bool:
    """
        DOCUMENTATION

        Returns true if all characters in the string are 
        spaces, or line-feeds, or tabs, or other things that look
        white when the text is printed onto a white sheet of paper.  
        
        The input parameter `itext` is any string of text. 
 
        The output is a Boolean (True or False)        
    """
    raise NotImplementedError() 

Behavior for the Empty String

Note that the empty string "" is a strange corner case.

Consider...

CASE
NUMBER
MATHEMATICIANS
SYMBOL
DESCIPTION BEHAVIOR
FOR
EMPTY STRING
1 of 2 There exists at least one character in the string which is not a white-space character False for the empty string
2 of 2 Either the string is empty, or there is at least one character in the string, and that character is white-space, and all other characters in the string are also white-space. True for the empty string

Implementation One
Using a For Loop

Implementation 1.1
One Return Statement Only

def is_pure_white(itext:str)  -> bool:
    r = True
    for ch in itext:
        if ch not in [' ', '\t', '\r', '\n', '\v', '\f']: 
            r = False
            break 
    return r    

Implementation 1.2
Two Return Statements

def is_pure_white(itext:str)  -> bool:
    for ch in itext:
        if ch not in [' ', '\t', '\r', '\n', '\v', '\f']: 
            return False
    return True   

Implementation Two
Remove Leading and Trailing White-Space

def is_pure_white(itext:str)  -> bool:
    """
        [
            INSTRUCTIONS 
            ON *HOW TO USE* THIS FUNCTION GO HERE

            NOTES ABOUT *HOW IT WORKS* ARE FORBIDDEN HERE
            DO NOT WRITE ABOUT THE INNER WORKINGS OR IMPLEMENTATION
        ]
    """
    # BEGIN DOCUMENTATION FOR IMPLEMENTATION (HOW IT WORKS)  
    #
    #     FIRST....
    #         Remove Leading and Trailing White-Space
    #
    #     SECONDLY....
    #         Check IF the Length of the string is zero.   
    # 
    # END DOCUMENTATION FOR IMPLEMENTATION (HOW IT WORKS)  
 
    text = itext.strip()
        if len(text) > 1:
            return False
        # else:
        #     empty string or all white space characters 
    return True   

Option Three
Using the Regular Expression Engine

import re # regular expression library 

def is_pure_white(itext:str) -> bool:
    pattern = "\s"
    spaces = re.findall(pattern, itext)
    status = len(spaces) == len(itext)
    return status

Option Four
Predicate Dispatching

This one requires a special library that most people don't have.

import casedispatching as kispatch 

@kispatch(lambda stryng: min(2, len(stryng)) ) 
def is_pure_white(itext:str) -> bool:
    praise NotImplementedError()  

###############################################################

@is_pure_white.register(0) 
def _(itext:str) -> bool:
    """ empty string """ 
    return True 

###############################################################

@is_pure_white.register(1) 
def _(ch:str) -> bool:
    status = ch in [' ', '\t', '\r', '\n', '\v', '\f']   
    return status   

################################################################

@is_pure_white.register(2) 
def _(itext:str) -> bool:
    # recursive implementation 
    for ch in itext:
        if not is_pure_white(ch) 
            return False
    return True  

A Simple Driver used for Testing Purposes

You can test your code, my code, or someone else's code using the following driver:

txt2 = "\t\t \n"
txt1 = "The rain in Spain\n\r"

cases = [txt1, txt2]

for case in cases:
    result = is_pure_white(case)
    print(repr(case).ljust(40), result)

Upvotes: -1

Ned Batchelder
Ned Batchelder

Reputation: 375844

The isspace() method on strings tells you this:

>>> "   ".isspace()
True
>>> " x  ".isspace()
False

Another option is to strip the ends:

if not s.strip():
    print "It was all whitespace!"

Upvotes: 10

Related Questions