PukiWiki


出力 の変更点


*出力 [#d51bd2af]
**Python [#q6a55be2]
print()を使う。コンマを使うとスペースを入れてくれる。
 >>> i = 256*256
 >>> print 'The value of i is', i
 The value of i is 65536

改行を出力したくない場合はコンマで終わらせる。
 >>> b = 3
 >>> print b,
***フォーマット [#q67ae8e7]
str()関数は人間が読みやすい形で出力する。
repr()関数はインタプリタが解釈しやすい形で出力する。
 >>> s = 'Hello, world.'
 >>> str(s)
 'Hello, world.'
 >>> repr(s)
 "'Hello, world.'"
 >>> str(0.1)
 '0.1'
 >>> repr(0.1)
 '0.10000000000000001'
 >>> x = 10 * 3.25
 >>> y = 200 * 200
 >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
 >>> print s
 The value of x is 32.5, and y is 40000...
 >>> # 文字列への repr() はクォートとバックスラッシュが付加される:
 ... hello = 'hello, world\n'
 >>> hellos = repr(hello)
 >>> print hellos
 'hello, world\n'
 >>> # repr() の引数は Python オブジェクトの場合もある:
 ... repr((x, y, ('spam', 'eggs')))
 "(32.5, 40000, ('spam', 'eggs'))"
***str.format() [#of52adfc]
 >>> print 'We are the {0} who say "{1}!"'.format('knights', 'Ni')
 We are the knights who say "Ni!"
 >>> print '{0} and {1}'.format('spam', 'eggs')
 spam and eggs
 >>> print '{1} and {0}'.format('spam', 'eggs')
 eggs and spam
 >>> print 'This {food} is {adjective}.'.format(
 ...     food='spam', adjective='absolutely horrible')
 This spam is absolutely horrible.
 >>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Gorg')
 The story of Bill, Manfred, and Gorg.
 >>>
 >>> import math
 >>> print 'The value of PI is approximately {0:.3f}.'.format(math.pi)
 The value of PI is approximately 3.142.
 >>> table = {'Sjoerd': 4127, 'Jack': 4089, 'Dcab': 7678}
 >>> for name, phone in table.items():
 ...     print '{0:10} ==> {1:10d}'.format(name, phone)
 ...
 Dcab       ==>       7678
 Jack       ==>       4089
 Sjoerd     ==>       4127
 >>>