python判断字符串是否为空

(转载)http://qianchenglong.github.io/2014/12/05/python%E5%88%A4%E6%96%AD%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA/


代码

  • 变量为字符串类型(优雅的方式)
1
2
3
4
if not string:
print('not empty')
else:
print('empty')
  • 变量类型不确定
1
2
3
4
if string == '':
print('not empty')
else:
print('empty')

参考

  1. https://docs.python.org/2/library/stdtypes.html#truth-value-testing
  2. http://stackoverflow.com/questions/9573244/most-elegant-way-to-check-if-the-string-is-empty-in-python

你可能感兴趣的:(python学习)