检查字符串是否只包含空格 [英] Check if string contains only whitespace

查看:55
本文介绍了检查字符串是否只包含空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试一个字符串是否只包含空格?

How can I test if a string contains only whitespace?

示例字符串:

  • <代码>""(空格,空格,空格)

<代码>"\t \n "(空格、制表符、空格、换行符、空格)

" \t \n " (space, tab, space, newline, space)

\n\n\n\t\n"(换行、换行、换行、制表符、换行)

"\n\n\n\t\n" (newline, newline, newline, tab, newline)

推荐答案

使用 str.isspace() 方法:

Use the str.isspace() method:

如果字符串中只有空格字符且至少有一个字符,则返回True,否则返回False.

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

如果在 Unicode 字符数据库中,字符是空格(请参阅 unicodedata),或者它的一般类别是 Zs(分隔符,空格"),或者它的双向类别是 WS、B 或 S 之一.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs ("Separator, space"), or its bidirectional class is one of WS, B, or S.

将其与处理空字符串的特殊情况结​​合起来.

Combine that with a special case for handling the empty string.

或者,您可以使用 str.strip() 并检查结果是否为空.

Alternatively, you could use str.strip() and check if the result is empty.

这篇关于检查字符串是否只包含空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆