text用法 - python plot text bbox
最優雅的方法來檢查在Python中的字符串是否為空? (13)
我發現硬編碼(sic)“”每次檢查一個空字符串都不太好。
乾淨的代碼方法
這樣做: foo == ""
是非常糟糕的做法。 ""
是一個神奇的價值。 你不應該檢查不可思議的價值(通常被稱為神奇數字 )
你應該做的是與描述性變量名稱進行比較。
描述性變量名稱
有人可能會認為“empty_string”是一個描述性變量名稱。 事實並非如此 。
在你去之前做empty_string = ""
並且認為你有一個很好的變量名來比較。 這不是“描述性變量名”的意思。
一個好的描述性變量名是基於其上下文的。 你必須考慮空字符串是什麼。
- 它從何而來。
- 為什麼在那裡。
- 為什麼你需要檢查它。
簡單的表單字段示例
您正在構建一個用戶可以輸入值的表單。 你想檢查用戶是否寫了一些東西。
一個好的變量名可能是not_filled_in
這使代碼非常可讀
if formfields.name == not_filled_in:
raise ValueError("We need your name")
徹底的CSV解析示例
您正在解析CSV文件,並希望將空字符串解析為None
(由於CSV完全是基於文本的,因此無法使用預定義的關鍵字就無法表示None
)
一個好的變量名可能是CSV_NONE
這使得代碼易於更改和適應,如果你有一個新的CSV文件代表None
與另一個字符串比""
if csvfield == CSV_NONE:
csvfield = None
沒有關於這段代碼是否正確的問題。 很明顯,它做它應該做的事情。
比較這一點
if csvfield == EMPTY_STRING:
csvfield = None
這裡的第一個問題是,為什麼空字符串應該得到特殊處理?
這將告訴未來的編碼人員,一個空字符串應始終被視為None
。
這是因為它混合了業務邏輯(什麼CSV值應該是None
)和代碼實現(我們實際比較的是什麼)
兩者之間需要分開關注 。
Python是否有類似空字符串變量的地方?
if myString == string.empty:
無論檢查空字符串值的最優雅方式是什麼? 我發現硬編碼""
每次檢查一個空字符串都不好。
if stringname:
字符串為空時為false
。 我想這不可能比這更簡單。
你可以看看這個在Python中分配空值或字符串
這是關於比較空的字符串的。 因此,而不是測試not
空虛,你可能會測試是你的字符串等於空字符串與""
空字符串...“
回應@ 1290。 抱歉,無法在評論中格式化塊。 None
值不是Python中的空字符串,也不是(空格)。 Andrew Clark的答案是正確的: if not myString
。 @rouble的答案是特定於應用程序的,並不回答OP的問題。 如果您對什麼是“空白”字符串採取特殊定義,您將遇到麻煩。 特別是,標準行為是str(None)
產生'None'
,一個非空字符串。
但是,如果您必須將None
和(空格)視為“空白”字符串,則這是更好的方法:
class weirdstr(str):
def __new__(cls, content):
return str.__new__(cls, content if content is not None else '')
def __nonzero__(self):
return bool(self.strip())
例子:
>>> normal = weirdstr('word')
>>> print normal, bool(normal)
word True
>>> spaces = weirdstr(' ')
>>> print spaces, bool(spaces)
False
>>> blank = weirdstr('')
>>> print blank, bool(blank)
False
>>> none = weirdstr(None)
>>> print none, bool(none)
False
>>> if not spaces:
... print 'This is a so-called blank string'
...
This is a so-called blank string
在不破壞字符串的預期bool
行為的情況下滿足@
對於期望apache StringUtils.isBlank或Guava Strings.isNullOrEmpty等行為的用戶:
if mystring and mystring.strip():
print "not blank string"
else:
print "blank string"
我會在剝離之前測試一下沒有。 另外,我會使用空字符串為False(或Falsy)的事實。 這種方法類似於Apache的StringUtils.isBlank或Guava的Strings.isNullOrEmpty
這是我將用來測試一個字符串是否為空或空或空白:
def isBlank (myString):
if myString and myString.strip():
#myString is not None AND myString is not empty or blank
return False
#myString is None OR myString is empty or blank
return True
而且,與測試字符串是否不是“非”的情況完全相反空或非空白:
def isNotBlank (myString):
if myString and myString.strip():
#myString is not None AND myString is not empty or blank
return True
#myString is None OR myString is empty or blank
return False
上述代碼更簡潔的形式:
def isBlank (myString):
return not (myString and myString.strip())
def isNotBlank (myString):
return bool(myString and myString.strip())
最優雅的方式可能是簡單地檢查它的真實性或者錯誤性,例如:
if not my_string:
但是,您可能需要去掉空白區域,因為:
>>> bool("")
False
>>> bool(" ")
True
>>> bool(" ".strip())
False
但是,您應該更清楚一點,除非您確定該字符串已通過某種驗證並且是可以按此方式進行測試的字符串。
測試空或空白字符串(較短的方式):
if myString.strip():
print("it's not an empty or blank string")
else:
print("it's an empty or blank string")
當您按行讀取文件並且想要確定哪一行是空的時,請確保您將使用.strip()
,因為“空行”中有新行字符:
lines = open("my_file.log", "r").readlines()
for line in lines:
if not line.strip():
continue
# your code for non-empty lines
這個怎麼樣? 也許它不是“最優雅的”,但它對我來說似乎相當完整,清晰和安全:
if (s is None) or (str(s).strip()==""): // STRING s IS "EMPTY"...
有這種可能性的例外或誤報嗎?
a = ''
b = ' '
a.isspace() -> False
b.isspace() -> True
not str(myString)
對於空的字符串,此表達式為True。 非空字符串,None和非字符串對像都會產生False,同時警告對象可能會重寫__str__以通過返回虛假值來阻止此邏輯。