Python中的输入(input)和输出打印

目录

最简单的打印

打印数字

打印字符

字符串的格式化输出

python中让输出不换行


以下的都是在Python3.X环境下的

使用 input 函数接收用户的输入,返回的是 str 字符串

最简单的打印

>>print("hello,word!")
hello,word!

打印数字

>>a=5
>>b=6
>>print(a)
>>print(a,b)
>>print(a+b)
5
5 6
11

打印字符

使用逗号连接会有空格,使用+号连接没有空格

>>a="hello,"
>>b="world!"
>>print(a,b)
>>print(a+b)
hello, world!
hello,world!

特别注意,当字符串是等于一个数的时候,这样两个字符串相加还是字符串。要把字符串转化为数字类型的才可以使用相加

>>a=input("请输入第一个数字:")         #20
>>b=input("请输入第二个数字: ")         #10
>>print(a,b)
>>print(a+b)
>>print(int(a)+int(b))
20 10
2010
30

字符串的格式化输出

>>name="小谢"
>>age="20"
>>print("{}的年龄是{}".format(name,age))
>>print("%s的年龄是%s"%(name,age))
小谢的年龄是20
小谢的年龄是20

>>print("i have a {1} and have a {0}".format("apple","orange"))
i have a orange and have a apple

>>print("i have a {one} and have a {two}".format(one="apple",two="orange"))
i have a apple and have a orange

>>print("i have a {} and have a {two}".format("apple",two="orange"))
i have a apple and have a orange

>>import math
>>print("{1:.3f} and {0.4f}".format(math.pi,math.e))
2.718 and 3.1416

#自动填充
>>print('12'.zfill(5))
>>print('-3.14'.zfill(7))
00012
-003.14


>>print('Hi,%s!'%input('Please enter your name!'))    //接收用户的输入,然后打印出来
Please enter your name!xie                   // xie 是用户输入的
Hi,xie! 

pprint打印

pprint模块用于打印 Python 数据结构. 当你打印特定数据结构时你会发现它很有用(输出格式比较整齐, 便于阅读)

import pprint
data = (
    "this is a string", [1, 2, 3, 4], ("more tuples",
    1.0, 2.3, 4.5), "this is yet another string"
    )

print(data)
print("*"*100)
pprint.pprint(data)
######################################
('this is a string', [1, 2, 3, 4], ('more tuples', 1.0, 2.3, 4.5), 'this is yet another string')
******************************************************************************************
('this is a string',
 [1, 2, 3, 4],
 ('more tuples', 1.0, 2.3, 4.5),
 'this is yet another string')

python中让输出不换行

原文地址:https://www.cnblogs.com/csnd/p/11807874.html