大神教你如何判斷Python中字串是否為空和null

安全劍客發表於2020-05-12
這篇文章主要介紹了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();

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

原文地址:

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31559985/viewspace-2691466/,如需轉載,請註明出處,否則將追究法律責任。

相關文章