Pythonの文字列を文字列に設定する1行のコードとは何ですか?文字列が空の場合は0ですか?文字列を0に設定する単一行のPythonコード空の場合は文字列
# line_parts[0] can be empty
# if so, set a to the string, 0
# one-liner solution should be part of the following line of code if possible
a = line_parts[0] ...
Pythonの文字列を文字列に設定する1行のコードとは何ですか?文字列が空の場合は0ですか?文字列を0に設定する単一行のPythonコード空の場合は文字列
# line_parts[0] can be empty
# if so, set a to the string, 0
# one-liner solution should be part of the following line of code if possible
a = line_parts[0] ...
a = line_parts[0] or "0"
これがデフォルト値を提供することが容易になり、素敵なPythonのイディオムの一つです。関数のデフォルト値によく使用されます:
def fn(arg1, arg2=None):
arg2 = arg2 or ["weird default value"]
+1新しいことを学びました。 –
明確にするために、ネッドの答えから明らかでない場合:文字列に関しては、空文字列は常にFalseと評価され、空でない文字列は常にTrueと評価されるため、この状況で完璧に動作します。 –
これを使うときは、 'arg2'が0または ''ではないことを確かめてください。 –
a = '0' if not line_parts[0] else line_parts[0]
より明確になるでしょう:a = line_parts [0]ならばline_parts [0] else '0' – recursive
@biznez答えを受け入れることを忘れないでください。 –
私は言っています:*は答えを受け入れるべきですか?人々があなたに代わって努力した後は、丁寧です。 –
文字列が空である(長さゼロの文字列を意味します)か、または**なし**を意味しますか? –