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

在 Python 中检查一个字符串是否只包含空格

Check if a string contains only whitespace in Python

使用该str.isspace()方法检查字符串是否仅包含空格,例如if my_str.isspace():. 如果字符串中只有空白字符且至少有一个字符,则str.isspace方法返回,否则返回。TrueFalse

主程序
my_str = ' ' # ✅ Check if a string contains only whitespace (str.isspace()) if my_str.isspace(): # 👇️ this runs print('The string contains only whitespace') else: print('The string does NOT only contain whitespace') # ---------------------------------------------------- # ✅ Check if a 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') # ---------------------------------------------------- # ✅ Check if a string contains only whitespace (str.strip()) if my_str.strip() == '': print('The string contains only whitespace')

第一个示例使用str.isspace方法检查字符串是否仅包含空格。

如果字符串只包含空白字符并且字符串中至少有一个字符,则str.isspace
方法返回,否则
返回。
TrueFalse

主程序
print(' '.isspace()) # 👉️ True print(''.isspace()) # 👉️ False print(' a '.isspace()) # 👉️ False

请注意,False如果字符串为空,则该方法会返回。

如果您考虑一个仅包含空格的空字符串,请检查该字符串的长度。

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

该示例检查字符串是否为空或仅包含空白字符。

我们使用了布尔or运算符,因此要使if块运行,必须满足任一条件。

或者,您可以使用该str.strip()方法。

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

检查字符串是否只包含空格:

  1. 使用该str.strip()方法从字符串中删除前导和尾随空格。
  2. 检查字符串是否为空。
  3. 如果字符串为空且所有空格都被删除,则它只包含空格。
主程序
my_str = ' ' if my_str.strip() == '': print('The string contains only whitespace')

The str.strip
method returns a copy of the string with the leading and trailing whitespace
removed.

The method doesn’t change the original string, it returns a new string. Strings
are immutable in Python.

If the result of calling the str.strip() method on the string returns an empty string, then the string contains only whitespace or is an empty string.

If you want to check if the string contains only whitespace characters and
contains at least one character, check if the string is truthy.

main.py
my_str = ' ' if my_str and my_str.strip() == '': print('The string contains only whitespace')

We used the boolean and operator, so for the if block to run, both
conditions have to be met.

The first condition checks if the string is truthy.

Empty strings are falsy, so the condition isn’t met for an empty string.