迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

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

作者:迹忆客 最近更新:2022/12/25 浏览次数:

使用 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')

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

第一个示例使用 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() 检查字符串是否只包含空格

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

  1. 使用 str.strip() 方法从字符串中删除前导和尾随空格。
  2. 检查字符串是否为空。
  3. 如果字符串为空且所有空格都被删除,则它只包含空格。
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 块,必须同时满足这两个条件。

第一个条件检查字符串是否为真。

空字符串是假的,因此不满足空字符串的条件。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便