Python 中检查字符串是否仅包含空格
使用 str.isspace() 方法检查字符串是否只包含空格,例如 if my_str.isspace():。 如果字符串中只有空白字符且至少有一个字符,则 str.isspace 方法返回 True,否则返回 False。
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')
第一个示例使用 str.isspace 方法检查字符串是否仅包含空格。
如果字符串只包含空白字符并且字符串中至少有一个字符,则 str.isspace 方法返回 True,否则返回 False。
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() 检查字符串是否只包含空格
检查字符串是否只包含空格:
- 使用 str.strip() 方法从字符串中删除前导和尾随空格。
- 检查字符串是否为空。
- 如果字符串为空且所有空格都被删除,则它只包含空格。
my_str = ' '
if my_str.strip() == '':
print('The string contains only whitespace')
str.strip 方法返回删除了前导和尾随空格的字符串副本。
该方法不会更改原始字符串,它会返回一个新字符串。 字符串在 Python 中是不可变的。
如果对字符串调用 str.strip() 方法的结果返回一个空字符串,则该字符串仅包含空格或者是一个空字符串。
如果要检查字符串是否仅包含空白字符且至少包含一个字符,请检查字符串是否为真。
my_str = ' '
if my_str and my_str.strip() == '':
print('The string contains only whitespace')
我们使用了布尔值 and 运算符,因此要运行 if 块,必须同时满足这两个条件。
第一个条件检查字符串是否为真。
空字符串是假的,因此不满足空字符串的条件。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。