文に空白文字以外が含まれているかどうかをテストしたい。これは私が現在使用しているものです:
if len(teststring.split()) > 0:
# contains something else than white space
else:
# only white space
これで十分ですか?それを行うより良い方法はありますか?
文に空白文字以外が含まれているかどうかをテストしたい。これは私が現在使用しているものです:
if len(teststring.split()) > 0:
# contains something else than white space
else:
# only white space
これで十分ですか?それを行うより良い方法はありますか?
str.isspace
ドキュメントによると、文字列には which と呼ばれるメソッドがあります。
[s] 文字列に空白文字のみがあり、少なくとも 1 文字ある場合は true、そうでない場合は false を返します。
つまり、次のことを意味します。
if teststring.isspace():
# contains only whitespace
あなたが望むことをします。
この目的には、 strip()関数を使用します。
if teststring.strip():
# non blank line
else:
# blank line
.strip() を使用するだけです。
空白のみの場合、結果の文字列は空になります。
if teststring.strip():
# has something other than whitespace.
else:
# only whitespace
あるいは、JBernardo が指摘したように、より明確に次のように言うこともできます。
if not teststring.isspace():
# has something other than whitespace
else:
# only whitespace.
if teststring.split():
print "not only whitespace!"
else:
print ":("