Python_print_format
一、Python中的输出
1、输出函数print()
# print()传入多个参数,参数与参数之间用逗号隔开,Python会依次打印字符串,而且逗号会输出一个空格,
>>> print("Hello","Python")
Hello Python
>>> print("5与40的和是",5 + 40)
5与40的和是 45
2、格式化输出 %
print('格式符号' % (表达式))
符号
说明
%c
格式化字符及其 ASCII 码
%s
格式化字符串
%d
格式化整数
%o
格式化无符号八进制数
%x
格式化无符号十六进制数
%X
格式化无符号十六进制数(大写)
%f
格式化浮点数字,可指定小数点后的精度
%e
用科学计数法格式化浮点数
%E
作用同 %e,用科学计数法格式化浮点数
%g
根据值的大小决定使用 %f 或 %e
%G
作用同 %g,根据值的大小决定使用 %f 或者 %E
2.1 字符串%s
print('我的名字是%s' % name)
print('我的年龄是%d岁' % age)
# 输出:
# 我的名字是ranran
# 我的年龄是20岁
2.2 浮点数%f
小数点后的位数
浮点数%f
默认输出小数点后6位.按照我们读小数习惯,一般是两位,则格式化符号位%.2f
,读3位就是%.3f
weight = 45.5
print('我的体重是%f公斤' % weight)
print('我的体重是%.2f公斤' % weight)
print('我的体重是%.3f公斤' % weight)
# 输出:
# 我的体重是45.500000公斤
# 我的体重是45.50公斤
# 我的体重是45.500公斤
百分号的实现
百分号:
%f%%
,且还要对浮点数进行操作。
scale = 0.1
print('数据的比例是%.2f' % scale)
# %的实现
print('数据的比例是%.1f%%' % (scale * 100))
#输出:
#数据的比例是0.10
#数据的比例是10.0%
2.3 整数%d
%03d 表示格式化输出3位数,不足三位的用零补全,超出3位原样输出
>>> stuid=1
>>> stuid2= 1000
>>> print("student id %d" % stuid)
student id 1
>>> print("student id %03d" % stuid)
student id 001
>>> print("student id %03d" % stuid2)
student id 1000
>>>
2.4 字符串补0
>>> str = "123"
>>> print(str.zfill(8))
00000123
# 还能把整数转化成字符来使用 zfill() 补零
>>> num = 123
>>> print(str(num).zfill(8))
00000123
3、f-字符串
格式:print(f'{表达式}')
# 这种方式仅支持python3.6以后的版本
>>> age = 20
>>> name = "xiaoming"
>>> weight = 45
>>> stuid=1
>>> print(" I am %s ,%d years old , my weigth is %.2f, my id is %03d " % (name,age,weight,stuid))
I am xiaoming ,20 years old , my weigth is 45.00, my id is 001
>>> print(f"I am {name}, {age} years old .....")
I am xiaoming, 20 years old .....
>>>
4、转义字符
\n:换行
\t:制表符,一个tab键(4个空格)的距离
>>> print("hello\nxiaoming")
hello
xiaoming
>>> print("\thello")
hello
>>>
5、print结束符
print('hello',end="\n"),也可以自己更改。
二、Python中的输入
1、input输入的特点
当程序执行到
input
,等待用户输入,输入完成之后才继续向下执行。在Python中,
input
接收用户输入后,一般存储到变量,方便使用。在Python中,
input
会把接受到的任意用户输入的任何类型数据
都当做字符串
处理。
password = input("input your password: ")
print(f"your password is {password}")
2、Python2.x和Python3.x的区别
Python2.x
Python3.x
input()
只接受数值(number)类型
接受的任何数据类型都当作字符串(str)
raw_input()
接收数值和字符串
没有
Last updated