Home > Enterprise >  Checking for Whitespaces in String
Checking for Whitespaces in String

Time:09-15

I wonder how to check for whitespaces in string. I know about isspace() method, which checks for any whitespace. But what about extra whitespace around string? For example:


def check_string(string):
    <...>
    return result

check_string(' The string has some whitespace.')
False

check_string(' Extra whitespace is not good. ')
False

check_string('This string is clean')
True

CodePudding user response:

Simple way with str.startswith/endswith:

def check_string(string):
    return not (string.startswith(' ') or string.endswith(' '))

check_string(' The string has some whitespace.')
# False

check_string(' Extra whitespace is not good. ')
# False

check_string('This string is clean')
# True

Or with a regex:

import re

def check_string(string):
    return bool(re.fullmatch('\S(.*\S)?', string))

check_string(' The string has some whitespace.')
# False

check_string(' Extra whitespace is not good. ')
# False

check_string('This string is clean')
#True

CodePudding user response:

The string.strip() function will remove both leading and trailing whitespace. Therefore:

def check_string(s):
  return len(s) == len(s.strip())
  • Related