python3 输入输出

190 阅读2分钟

输出

符号说明
%s字符串
%d有符号十进制整数
%u无符号十进制整数
%f浮点数
%c字符
%o八进制整数
%x十六进制整数小写格式ox
%X十六进制整数大小格式OX
%e科学计数法,小写格式e
%E科学计数法,大写格式
%g%f和%e的简写
%G%f和%E的简写
name = "蛮王"
age = 18
weight = 100.3
print("age is %d "% age)
print("name is %s" % name)
print("weight is %f" % weight)
print("weight is %.3f" % weight)

# 如果要格式化输出多个值,则通过括号包含
print("name is %s age is %d" % (name, age))

# 整数对齐,在%后面添加数字,则会用空格占位,也

print("%d" % 10)
print("%04d" % 1) # 空余的位置用0填充
print("%4d" % 10)
print("%4d" % 100)
print("%4d" % 1000)
print("%4d" % 10000)
print("%4d" % 100000)

python3.6之后可以使用f表达式。其中大括号中可以是值,也可以是表达式。

name = "二哈"
age = 18
print(f"name is {name} age is {age}")

转义字符

print("你好\n中国。\t 你好\t 世界")

print换行原理

print("hello") #自带换行符

print("hello", end="\n") #上面的缩写形式

输入


# input中的字符串为提示信息,所有的输入内容都是字符串
name = input("请输入名字")
print(name)

# 类型转换
age = input("输入年龄")
print(f"age is {age} type of age is {type(age)}")
# 转成整数
new_age = int(age)
print(f"new_age is {new_age} type of new_age is {type(new_age)}")

"""
请输入名字haha
haha
输入年龄18
age is 18 type of age is <class 'str'>
new_age is 18 type of new_age is <class 'int'>
"""

类型转换

# 转浮点
a = 10
b = "123"

# 这里会报错
# c = "123a"
d = 12.0
# print(f"{float(a)} {float(b)} {float(c)} {float(d)}")
print(f"{float(a)} {float(b)} {float(d)}") # 10.0 123.0 12.0
# 转str
a = 10
b = 10.1
c = "120"
print(f"{str(a)} {str(b)} {str(c)}")
print(f"{type(str(a))} {type(str(b))} {type(str(c))}")

"""
10 10.1 120
<class 'str'> <class 'str'> <class 'str'>
"""
# 转tuple

# a是整数,不能迭代,因此无法转成tuple
#a = 10
b = [1,2,3] # 列表可以转tuple
c = (1,2,3) # 元组可以转元组
d = {"name":"zhangsan"} # 字典可以转元组,但是只有Key
e = {"name", 123} # 集合可以转tuple
#print(f"{tuple(a)} {tuple(b)} {tuple(c)}")
print(f"{tuple(b)} {tuple(c)} {tuple(d)} {tuple(e)}") #(1, 2, 3) (1, 2, 3) ('name',) (123, 'name')
# 转list

# 元组转list
a = (10, "你好", 10.1)
print(f"{list(a)} {type(list(a))}")

# 集合转list
b = {1, "Hello", 100}
print(f"{list(b)} {type(list(b))}")

# 字典转list
c = {"name":"小明"}
print(f"{list(c)} {type(list(c))}")

# 语法错误
#d = 10
#print(f"{list(d)} {type(list(d))}")
#eval会根据字符串自动生成对应的数据类型的数据
print(f'{eval("1.1")} {type(eval("1.1"))}') #1.1 <class 'float'>
print(f'{eval("1")} {type(eval("1"))}') #1 <class 'int'>