0

How to check if a String equals to Empty, and to a different string constant (such as '\n', '\t', etc.) with Python?

This is what I used:

if not text or text == '\n' or text == '\t':
    log.debug("param 'text': " + text)
    return None

how to do it better?

Olga
  • 1,351
  • 2
  • 23
  • 34
  • Possible duplicate of: http://stackoverflow.com/questions/9573244/most-elegant-way-to-check-if-the-string-is-empty-in-python – ShuklaSannidhya Apr 26 '13 at 06:29
  • Not really a duplicate. The other question is specifically concerned with comparing against "". – Vishal Apr 26 '13 at 09:08

3 Answers3

2
if not text or text.isspace():
    # empty param text

Regarding isspace, it returns True if there are only whitespace characters and at least one character.

Jared
  • 24,139
  • 7
  • 52
  • 61
2
if not text.rstrip():
  log.warning("Empty param 'text': " + text)
  return None

str.rstrip([chars]): The method rstrip() returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters).

Vishal
  • 2,958
  • 2
  • 31
  • 45
0
if not text in (None, '', '\n','\t'):
apaul
  • 15,894
  • 8
  • 45
  • 79
vlad-ardelean
  • 7,274
  • 12
  • 75
  • 115