2010-01-25 155 views
7

好的,這裏有一些簡單的點。 PyBinding附帶這個腳本:字符串爲空或空

def IsNotNull(value): 
    return value is not None 

它很接近,但我想要的是這個。

bool IsNotNullOrEmpty(string value) { 
    return (value != null) && (value.Length > 0); 
} 
+0

好,.NET包括String.IsNullOrEmpty。這會起作用嗎? – ojrac 2010-01-25 02:22:55

回答

16

要檢查字符串是否爲空,您可以使用len。試試這個:

def IsNotNull(value): 
    return value is not None and len(value) > 0 
+0

錯了。你甚至打擾了這個代碼嗎? – 2010-01-25 01:58:53

+0

你走了,我回滾到我原來的答案。我刪除了我的帖子,然後用我認爲是「Pythonic」的解決方案替換了它,其中涉及'not not'。 – 2010-01-25 02:08:15

+1

-1這不是Python作爲無必要的,「」是假的Python:http://docs.python.org/library/stdtypes.html#truth-value-testing – 2010-01-31 18:41:24

0

我認爲,

if IsNotNull(value) { 

相當於

if not value: 

字符串。所以我認爲這個函數在python中是沒有必要的。

1
def IsNotNullString(s): 
    return bool(s) 

Rules of Python boolean conversion.

+0

沒有工作。空字符串仍然回傳爲True。 – 2010-01-25 01:52:00

+0

@JonathanAllen我只是在python解釋器中運行它,它爲我工作。你在哪個版本的Python中獲得了True?我正在使用2.7.3 – Saurav 2012-05-16 00:41:22

5

你不應該在一個函數做這個。相反,你應該只使用:

if someStringOrNone: 
+0

沒有工作。空字符串仍然回傳爲True。 – 2010-01-25 01:54:02

+5

這是首選的Pythonic版本,它完美適用於Python的字符串。它可能不適用於你的唯一原因是,如果你將一些與Python字符串不兼容的.NET類型傳遞給該函數。 – 2010-01-25 02:13:04

+0

@Jonathan我不認爲你會傳遞空串來測試。正如Ignacio向您展示的那樣,它適用於空弦。你能告訴我們代碼空字符串評估爲True嗎?我認爲那會是一個錯誤。 – 2010-01-31 18:28:58

3

如果是IronPython的,那麼爲什麼不使用來自System.String IsNullOrEmpty的默認實現?

import clr 
clr.AddReference('System') 
import System 
System.String.IsNullOrEmpty('') # returns True 
System.String.IsNullOrEmpty(None) # returns True 
System.String.IsNullOrEmpty('something') # returns False