文章首发及后续更新:https://mwhls.top/3235.html
新的更新内容请到mwhls.top查看。
无图/无目录/格式错误/更多相关请到上方的文章首发页面查看。
目录 1. 如何确定字符串为空? 2. How to check if the string is empty?stackoverflow热门问题目录
如有翻译问题欢迎评论指出,谢谢。
Joan Venge asked:
if myString == string.empty:
"“
不太合适。Answers:
Andrew Clark – vote: 2602
空字符串为false(参考 python 2 或 python 3 ),这意味着它在布尔语句下被判断为false,所以可以这么做:
if not myString:
如果你确定变量是字符串的话,这个方法更好一点。但如果它可能是其他类型,还是得选择用myString == “”
。见文档Truth Value Testing中布尔语句下其它等效为false的变量值。
zenpoy – vote: 474
见 PEP 8 标准, “Programming Recommendations” 节:
- 对于序列来说(字符串、列表、元组),空序列为false。
所以可以这么做
if not some_string:
或:
if some_string:
但要澄清,空/非空序列会在布尔语句下被认为是False/True
,但并不等价。
Bartek – vote: 288
最优雅的方式可能是确定它是true还是false,例如:
if not my_string:
不过你可能需要strip掉空白字符,因为:
>>> bool(”") False >>> bool(" “) True >>> bool(” ".strip()) False
更明确的说,你要确保字符串会通过某种验证,并且字符串可以以上面形式通过测试。
Joan Venge asked:
if myString == string.empty:
""
every time for checking an empty string not as good.""
不太合适。Answers:
Andrew Clark – vote: 2602
Empty strings are falsy (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:
空字符串为false(参考 python 2 或 python 3 ),这意味着它在布尔语句下被判断为false,所以可以这么做:
if not myString:
This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use myString == ""
. See the documentation on Truth Value Testing for other values that are false in Boolean contexts.
如果你确定变量是字符串的话,这个方法更好一点。但如果它可能是其他类型,还是得选择用myString == ""
。见文档Truth Value Testing中布尔语句下其它等效为false的变量值。
zenpoy – vote: 474
From PEP 8, in the “Programming Recommendations” section:
见 PEP 8 标准, “Programming Recommendations” 节:
- For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
对于序列来说(字符串、列表、元组),空序列为false。
So you should use:
所以可以这么做
if not some_string:
or:
或:
if some_string:
Just to clarify, sequences are evaluated to False
or True
in a Boolean context if they are empty or not. They are not equal to False
or True
.
但要澄清,空/非空序列会在布尔语句下被认为是False/True
,但并不等价。
Bartek – vote: 288
The most elegant way would probably be to simply check if its true or falsy, e.g.:
最优雅的方式可能是确定它是true还是false,例如:
if not my_string:
However, you may want to strip white space because:
不过你可能需要strip掉空白字符,因为:
>>> bool("") False >>> bool(" ") True >>> bool(" ".strip()) False
You should probably be a bit more explicit in this however, unless you know for sure that this string has passed some kind of validation and is a string that can be tested this way.
更明确的说,你要确保字符串会通过某种验证,并且字符串可以以上面形式通过测试。