Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检查字符串是否包含除空格以外的任何内容_Python_Python 3.x_String - Fatal编程技术网

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 然后,您可以通过检查新字符串的长度轻松地检查所需内容 >>>

如何检查python中的字符串中是否有文本或只有空格

例如:

应返回
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

(该函数是可选的,但在示例中非常有用)

查看您尝试了什么?你具体需要什么帮助?