1. 程式人生 > 程式設計 >Python判斷字串是否為空和null方法例項

Python判斷字串是否為空和null方法例項

判斷python中的一個字串是否為空,可以使用如下方法

1、使用字串長度判斷

len(s) ==0 則字串為空

#!/user/local/python/bin/python
# coding=utf-8
test1 = ''
if len(test1) == 0:
  print '字串TEST1為空串'
else:
  print '字串TEST1不是空串,TEST1:' + test1

2、isspace判斷是否字串全部是空格

Python isspace() 方法檢測字串是否只由空格組成。

#!/user/local/python/bin/python
# coding=utf-8

str = "    "; 
print str.isspace();

str = "This is string example....wow!!!";
print str.isspace();

True
False

3、字串去空格及去指定字元

去兩邊空格:str.strip()

去左空格:str.lstrip()

去右空格:str.rstrip()

#!/user/local/python/bin/python
# coding=utf-8
str = "    "; 
print str.strip();
str = "This is string example....wow!!! ";
print str.strip();

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。