Python基础之数据类型转换及格式化输出(1)

  1. 数据类型转换
a = 1.222
print (str(a))
print (int(a))
print (float(a))

结果显示:
1.222
1
1.222
  1. 数据格式化显示
    (1)整数显示
m = 12
print("|%d|" % m)
print("|%4d|" % m)
print("|%-4d|" % m)
print("|%04d|" % m)
print("|%-04d|" % m)

结果显示:
|12|
|  12|
|12  |
|0012|
|12  |


m2 = 12345
print("|%d|" % m2)
print("|%4d|" % m2)
print("|%-4d|" % m2)
print("|%04d|" % m2)
print("|%-04d|" % m2)

结果显示:
|12345|
|12345|
|12345|
|12345|
|12345|

(2)日期显示

year = 2018
month = 10
day = 19
hour = 8
minute = 12
second = 0
print("Time:  %04d-%02d-%02d  %02d:%02d:%02d" % (year,month,day,hour,minute,second))

结果显示:
Time:  2018-10-19  08:12:00

(3)浮点数显示

m = 12.57432
print("|%f|" % m)
print("|%8.1f|" % m)
print("|%8.2f|" % m)
print("|%-8.1f|" % m)
print("|%-8.0f|" % m)
print("|%10.8f|" % m)

结果显示:
|12.574320|
|    12.6|
|   12.57|
|12.6    |
|13      |
|12.57432000|

(4)字符串显示

m = 'abcd'
print("|%s|" % m)
print("|%8s|" % m)
print("|%-8s|" % m)

结果显示:
|abcd|
|    abcd|
|abcd    |

你可能感兴趣的:(Python,Python,格式化输出)