# Python 中检查字符串是否仅包含空格

``````my_str = '       '

# ✅ 检查字符串是否只包含空格 (str.isspace())
if my_str.isspace():
# 👇️ this runs
print('The string contains only whitespace')
else:
print('The string does NOT only contain whitespace')

# ----------------------------------------------------

# ✅ 检查字符串是否不仅包含空格
if not my_str.isspace():
print('The string does NOT only contain whitespace')
else:
# 👇️ this runs
print('The string contains only whitespace')
# ----------------------------------------------------

# ✅ 检查字符串是否只包含空格 (str.strip())
if my_str.strip() == '':
print('The string contains only whitespace')
`````` ``````print('  '.isspace()) # 👉️ True

print(''.isspace()) # 👉️ False

print(' a  '.isspace()) # 👉️ False
``````

``````my_str = '       '

if len(my_str) == 0 or my_str.isspace():
print('The string contains only whitespace')
``````

## 使用 str.strip() 检查字符串是否只包含空格

1. 使用 str.strip() 方法从字符串中删除前导和尾随空格。
2. 检查字符串是否为空。
3. 如果字符串为空且所有空格都被删除，则它只包含空格。
``````my_str = '       '

if my_str.strip() == '':
print('The string contains only whitespace')
``````

str.strip 方法返回删除了前导和尾随空格的字符串副本。

``````my_str = '       '

if my_str and my_str.strip() == '':
print('The string contains only whitespace')
``````
{"ft_lang_label":"__label__zh","ft_lang_prob":0.8368662,"math_prob":0.58816427,"size":1813,"snap":"2022-40-2023-06","text_gpt3_token_len":860,"char_repetition_ratio":0.21614152,"word_repetition_ratio":0.19565217,"special_character_ratio":0.28792056,"punctuation_ratio":0.119521916,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.95390415,"pos_list":[0,1,2],"im_url_duplicate_count":[null,1,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-02-03T17:18:42Z\",\"WARC-Record-ID\":\"<urn:uuid:12721445-be77-4da8-b649-ecccef7d1048>\",\"Content-Length\":\"96900\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:58715164-9925-42bc-bdec-fa5ceb8d1c41>\",\"WARC-Concurrent-To\":\"<urn:uuid:34dd2de0-99ee-4d40-a1df-82a876d23e7c>\",\"WARC-IP-Address\":\"101.132.179.38\",\"WARC-Target-URI\":\"https://www.zadmei.com/pzjczfcs-2.html\",\"WARC-Payload-Digest\":\"sha1:BLWZV6VJ5XUM4P73AUVMF6IFRGKA6KVZ\",\"WARC-Block-Digest\":\"sha1:DC2ST4RKJTNNJQIJNALAFZV7GZKBI3C2\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-06/CC-MAIN-2023-06_segments_1674764500058.1_warc_CC-MAIN-20230203154140-20230203184140-00244.warc.gz\"}"}