文字列内での変数展開
文字列内での変数展開の使い方を解説します.
変数を%?で置くときの, ?の部分は, 文字列ならs, 整数ならd, 浮動小数点なら, fになります.
print文内での変数展開
まず, 変数一つの時は,
>>> x = "hello world"
>>> print "x: %s" % x
x: hello world
次に, 変数が2つ以上の時.
>>> x = 12.34
>>> y = 100
>>> z = "hello"
>>> print "x: %f, y: %d, z: %s" % (x, y, z)
x: 12.340000, y: 100, z: hello
数字は, 文字列としても読めるようです.
>>> x = 12.34
>>> y = 100
>>> z = "hello"
>>> print "x: %s, y: %s, z: %s" % (x, y, z)
x: 12.34, y: 100, z: hello
ちょっと違った書き方もできます.
>>> x = 12.34
>>> y = 100
>>> z = "hello"
>>> print "x: %(x)f, y: %(y)d, z: %(z)s" % locals()
x: 12.340000, y: 100, z: hello
print文でなくてもつかえます
>>> h = "hello"
>>> w = "world"
>>> hw = "%s %s" % (h, w)
>>> print hw
hello world