译(三十三)-Python确定空字符串
如有翻译问题欢迎评论指出,谢谢。
如何确定字符串为空?
Joan Venge asked:
- Python里面有类似下面的办法来判断空字符串吗:
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
更明确的说,你要确保字符串会通过某种验证,并且字符串可以以上面形式通过测试。
How to check if the string is empty?
Joan Venge asked:
- Does Python have something like an empty string variable where you can do:
Python里面有类似下面的办法来判断空字符串吗: if myString == string.empty:
- Regardless, what\'s the most elegant way to check for empty string values? I find hard coding
""
every time for checking an empty string not as good.
或者有没有最优雅的方式来确定空字符串?我觉得直接用""
不太合适。
- Does Python have something like an empty string variable where you can do:
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
orTrue
in a Boolean context if they are empty or not. They are not equal toFalse
orTrue
.
但要澄清,空/非空序列会在布尔语句下被认为是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.
更明确的说,你要确保字符串会通过某种验证,并且字符串可以以上面形式通过测试。
共有 0 条评论