chap02/sample5.py

サンプルコードのダウンロード

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4###
 5### printf形式
 6###
 7s = '%s is more powerful than %s' % ('Python', 'Fortran')
 8print(s)
 9
10i = 2021
11a = 3.1415
12b = 2.7182
13print("i  = %-5d" % (i))
14print("pi = %4.2f" % (a))
15print("e  = %5.3f" % (b))
16
17###
18### format()
19###
20# "Python is more powerful than Fortran" が出力される
21s = "{} is more powerful than {}".format('Python', 'Fortran')
22print(s)
23
24# "Fortran is more powerful than Python" が出力される
25s = "{1} is more powerful than {0}".format('Python', 'Fortran')
26print(s)
27
28print("i  = {:-5d}".format(i))
29print("pi = {:4.2f}".format(a))
30print("e  = {:5.3f}".format(b))