4

文に空白文字以外が含まれているかどうかをテストしたい。これは私が現在使用しているものです:

if len(teststring.split()) > 0:
    # contains something else than white space
else:
   # only white space

これで十分ですか?それを行うより良い方法はありますか?

4

4 に答える 4

14

str.isspaceドキュメントによると、文字列には which と呼ばれるメソッドがあります。

[s] 文字列に空白文字のみがあり、少なくとも 1 文字ある場合は true、そうでない場合は false を返します。

つまり、次のことを意味します。

if teststring.isspace():
    # contains only whitespace

あなたが望むことをします。

于 2012-06-21T01:43:58.020 に答える
7

この目的には、 strip()関数を使用します。

  if teststring.strip():
      # non blank line
  else:
      # blank line
于 2012-06-21T01:42:02.783 に答える
2

.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.
于 2012-06-21T01:43:14.313 に答える
1
 if teststring.split():
      print "not only whitespace!" 
 else:
     print ":("
于 2012-06-21T01:43:10.620 に答える