Python 如何检查字符串是否包含除空格以外的任何内容
如何检查python中的字符串中是否有文本或只有空格 例如:Python 如何检查字符串是否包含除空格以外的任何内容,python,python-3.x,string,Python,Python 3.x,String,如何检查python中的字符串中是否有文本或只有空格 例如: ”应返回False “test”应返回True teststring = " " print(teststring.isspace()) # True “tes t”应返回Truestr.strip()函数将从字符串中删除任何前导或尾随空格 teststring = " " print(teststring.isspace()) # True 然后,您可以通过检查新字符串的长度轻松地检查所需内容 >>>
”
应返回False
“test”
应返回True
teststring = " "
print(teststring.isspace())
# True
“tes t”
应返回True
str.strip()
函数将从字符串中删除任何前导或尾随空格
teststring = " "
print(teststring.isspace())
# True
然后,您可以通过检查新字符串的长度轻松地检查所需内容
>>> 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
(该函数是可选的,但在示例中非常有用)查看您尝试了什么?你具体需要什么帮助?