今日からプログラミングを始めたのですが、Pythonでこんな問題があります。かなり馬鹿げたことですが、どうすればいいのかわかりません。printコマンドを使うと、私が望むものは何でも表示され、その後別の行に進みます。例えば、次のようになります。
print "this should be"; print "on the same line"
を返すべきです。
これは同じ行にあるべきです。
を返しますが、代わりに
と表示されます。 同一行に
もっと正確に言うと、私は if
を使って、ある数字が 2 であるかどうかを示すプログラムを作ろうとしていました。
def test2(x):
if x == 2:
print "Yeah bro, that's tottaly a two"
else:
print "Nope, that is not a two. That is a (x)"
しかし、最後の (x)
を入力された値として認識せず、正確に: "(x)" (括弧付きの文字)と表示してしまいます。これを動作させるには、次のように書かなければなりません。
print "Nope, that is not a two. That is a"; print (x)
そして、例えば、test2(3)
と入力すると、次のようになります。
Nope, that is not a two, that is a 3
ですから、Pythonに印字行内の(x)を数字として認識させるか、2つの別々のものを同じ行に印字する必要があります。 くだらない質問で申し訳ありませんが、よろしくお願いします。
重要な注意事項:バージョン2.5.4**を使用しています。
また、print "Thing" , print "Thing2"` とすると、2回目の印刷で "Syntax error" と表示されます。
Python 3.x**では、print()
関数のend
引数を使って、改行文字が出力されないようにすることができます。
print("Nope, that is not a two. That is a", end="")
Python 2.xでは、末尾にカンマを使用できます。
print "this should be",
print "on the same line"
しかし、単に変数を表示するためには必要ありません。
print "Nope, that is not a two. That is a", x
これは Python 3 で end=" "
を使っているのと同じです。 スペース文字を抑制するには、次のようにします。
from __future__ import print_function
を使ってPython 3のprint関数にアクセスするか、sys.stdout.write()
を使います。
新しい行が表示されないように、末尾にカンマを入れてください。
print "this should be"; print "on the same line"
とする必要があります。
print "this should be", "on the same line"
さらに、渡している変数を目的の文字列の最後にくっつけるだけで、次のようになります。
print "Nope, that is not a two. That is a", x
を使うこともできます。
print "Nope, that is not a two. That is a %d" % x #assuming x is always an int
演算子(modulo)を使った文字列のフォーマットに関する追加のドキュメントにアクセスできます。