简体   繁体   中英

Check whether a string is empty (or spaces)

I have a string which is :

>>> a = "           "
>>> a.isspace()
False
>>> a
'\xe2\x80\x83\xe2\x80\x83             \xe2\x80\x83\xe2\x80\x83             \xe2\x80\x83\xe2\x80\x83             \xe2\x80\x83\xe2\x80\x83             \xe2\x80\x83\xe2\x80\x83             \xe2\x80\x83\xe2\x80\x83             \xe2\x80\x83\xe2\x80\x83             \xe2\x80\x83\xe2\x80\x83             \xe2\x80\x83\xe2\x80\x83             \xe2\x80\x83\xe2\x80\x83             \xe2\x80\x83\xe2\x80\x83             '
>>> print a
                                                                                                                                                                     
>>> 

As we can see, when I print string a, it is all spaces. However, using isspace() cannot check it is a string full of spaces. How can I detect such kind of string to be a "space string"?

You do not have a string containing only whitespace characters. You have a bytestring containing the UTF-8 encoding of a Unicode string containing only whitespace characters.

Decoding the bytes in UTF-8 produces a Unicode string that reports True for isspace :

>>> a.decode('utf-8').isspace()
True

but don't just slap decode('utf-8') into your code ad-hoc and hope it works.

Keep track of whether you're using Unicode or bytestrings at all times. Generally, work in Unicode, convert bytestring input to Unicode immediately, and only convert Unicode to bytestrings as it leaves your code.

str.isspace() checks whether or not a string is only a space so it would not work if there are other characters present.

You can use str.contains(' ') to check if there are spaces in your string or

if ' ' in str:
    #do something
import re
if re.search(r"^\s+$"):
    print "All Spaces"

The regex above will match any string that contains only the following characters:

ASCII space , tab , line feed , carriage return , vertical tab , form feed


Alternatively, and probably more efficient, you can use strip() :

a = "             ".strip()
if not a:
    print "All spaces"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM