【发布时间】:2019-10-29 13:55:02
【问题描述】:
如何检查python中的字符串中是否有文本或只有空格?
例子:
" " 应该返回 False
"test" 应该返回 True
"tes t " 应该返回 True
【问题讨论】:
-
你试过什么?您具体需要哪些帮助?
标签: python python-3.x string
如何检查python中的字符串中是否有文本或只有空格?
例子:
" " 应该返回 False
"test" 应该返回 True
"tes t " 应该返回 True
【问题讨论】:
标签: python python-3.x string
teststring = " "
print(teststring.isspace())
# True
【讨论】:
str.strip() 函数将从您的字符串中删除任何前导或尾随空格。
然后你可以通过检查新字符串的长度轻松检查你想要的内容。
>>> my_str_with_space = ' \r\n string \r\n '
>>> my_str_with_space
' \r\n string \r\n '
>>> my_str = my_str_with_space.strip()
>>> my_str
'string'
所以创建一个简单的函数来通过检查字符串长度来检查字符串是否为空。
>>> def str_not_empty(s):
... return bool(len(s))
然后使用它。
>>> str_not_empty(my_str)
True
>>> str_empty = ''
>>> str_not_empty(str_empty)
False
(该函数是可选的,但对示例很有用)
【讨论】: