I have a CSV file where fields are delimited with a comma. The fields of this CSV file contains the attributes of Permanent Survey Marks and I’ve created a GIS python script to convert it to a table that is stored it in our Enterprise GIS Spatial Database (SQL Server).

Within each row, there are some field’s that contain whitespace only. For example, part of a typical line shown here:

, ,N,NRM ,SP109773 , ,CK3693 , ,CK3543 ,

I discovered that these whitespace fields were being stored in the table as a string of whitespace characters. I needed to determine if each field had whitespace characters only and then make the script store these particular fields with a null value in the table. I came up with this function to do the job:

def isWhiteSpaceString(string):

    """  Check if string only contains whitespace characters.

         Input:   string value

         Output:  Returns True if string contains only whitespace
                  characters otherwise returns False


    if (str == None):
        return False

    flag = 0
    for char in string:
        if char == " ":
            flag = 1
    if flag == 0:
        # string only contains whitespace characters
        return True
        # string contains as least one alphanumeric character
        return False

# ---------------------------------------------------------------------------- #

a = 'abcdefg12345'
b = 'abcdefg12345     '
c = '     abcdefg12345'
d = '!                '
e = '                 '

print isWhiteSpaceString(a)
print isWhiteSpaceString(b)
print isWhiteSpaceString(c)
print isWhiteSpaceString(d)
print isWhiteSpaceString(e)

*** Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32. ***

This works but I’m looking for alternative solution that might be a little more compact or even more efficient.

str method strip() will remove leading and trailing whitespace characters. If a string only has whitespace characters, strip() will remove them all and it will evaluate False. Example:

>>> not 'abcdefg12345     '.strip()
>>> not '        '.strip()
This question has already been answered. Start a new discussion instead.