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,395
  • 2
  • 25
  • 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
  • 25,627
  • 7
  • 56
  • 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
  • 3,178
  • 2
  • 34
  • 47
0
if not text in (None, '', '\n','\t'):
apaul
  • 16,092
  • 8
  • 47
  • 82
vlad-ardelean
  • 7,480
  • 15
  • 80
  • 124