Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains only whitespace

How can I test if a string contains only whitespace?

Example strings:

  • " " (space, space, space)

  • " \t \n " (space, tab, space, newline, space)

  • "\n\n\n\t\n" (newline, newline, newline, tab, newline)

like image 595
bodacydo Avatar asked Mar 08 '10 22:03

bodacydo


People also ask

How do I check if a string contains a space in Python?

Python isspace() method is used to check space in the string. It returna true if there are only whitespace characters in the string. Otherwise it returns false. Space, newline, and tabs etc are known as whitespace characters and are defined in the Unicode character database as Other or Separator.

How do I check if a string contains only spaces in PHP?

PHP | ctype_space() Function A ctype_space() function in PHP is used to check whether each and every character of a string is whitespace character or not. It returns True if the all characters are white space, else returns False.

How do you check if a string has a space in Java?

In order to check if a String has only unicode digits or space in Java, we use the isDigit() method and the charAt() method with decision making statements. The isDigit(int codePoint) method determines whether the specific character (Unicode codePoint) is a digit. It returns a boolean value, either true or false.


2 Answers

Use the str.isspace() method:

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.

Combine that with a special case for handling the empty string.

Alternatively, you could use str.strip() and check if the result is empty.

like image 124
Vladislav Avatar answered Oct 14 '22 03:10

Vladislav


str.isspace() returns False for a valid and empty string

>>> tests = ['foo', ' ', '\r\n\t', ''] >>> print([s.isspace() for s in tests]) [False, True, True, False] 

Therefore, checking with not will also evaluate None Type and '' or "" (empty string)

>>> tests = ['foo', ' ', '\r\n\t', '', None, ""] >>> print ([not s or s.isspace() for s in tests]) [False, True, True, True, True, True] 
like image 40
John Machin Avatar answered Oct 14 '22 03:10

John Machin