输出函数 print()简介:
- 首先明确一下,Python3中的print函数必须加上(),而Python2不需要
#Python2的运行结果:
print 'Python', python_version()
print 'Hello, World!'
print('Hello, World!')
print "text", ; print 'print more text on the same line'
#打印结果:
Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line
#Python3的运行结果:
print('Python', python_version())
print('Hello, World!')
print("some text,", end="")
print(' print more text on the same line')
#打印结果
Python 3.4.1
Hello, World!
some text, print more text on the same line
2. print() 的参数类型
print() 可以输出所有的对象
>>> print(1) #直接输出数值
1
>>> print("Hello World") #输出字符串
Hello World
>>> x = 12
>>> print(x) #输出int变量
12
>>> s = 'Hello'
>>> print(s) #输出字符串变量
Hello
>>> L = [1,2,'a']
>>> print(L) #输出List列表
[1, 2, 'a']
>>> t = (1,2,'a')
>>> print(t) #输出tuple元组
(1, 2, 'a')
>>> d = {'a':1, 'b':2}
>>> print(d) #输出dict字典
{'a': 1, 'b': 2}
3. print 的格式化输出
>>> s
'Hello'
>>> x = len(s)
>>> print("The length of %s is %d" % (s,x))
The length of Hello is 5
python字符串格式化符号:
| 符 号 | 描述 |
|---|---|
| %c | 格式化字符及其ASCII码 |
| %s | 格式化字符串 |
| %d | 格式化整数 |
| %u | 格式化无符号整型 |
| %o | 格式化无符号八进制数 |
| %x | 格式化无符号十六进制数 |
| %X | 格式化无符号十六进制数(大写) |
| %f | 格式化浮点数字,可指定小数点后的精度 |
| %e | 用科学计数法格式化浮点数 |
| %E | 作用同%e,用科学计数法格式化浮点数 |
| %g | %f和%e的简写 |
| %G | %f 和 %E 的简写 |
| %p | 用十六进制数格式化变量的地址 |
格式化操作符辅助指令:
| 符号 | 功能 |
|---|---|
| * | 定义宽度或者小数点精度 |
| - | 用做左对齐 |
| + | 在正数前面显示加号( + ) |
| <sp> | 在正数前面显示空格 |
| # | 在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X') |
| 0 | 显示的数字前面填充'0'而不是默认的空格 |
| % | '%%'输出一个单一的'%' |
| (var) | 映射变量(字典参数) |
| m.n. | m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话) |
4. print() 默认总是换行输出的
>>> for x in range(0,5):
print(x)
0
1
2
3
4
若想要不换行输出,应写成print(x, end = ''),其中end代表print函数最后打印的内容
>>> for x in range(0,5):
print (x,end = '')
01234
5. print()可以直接打印一个表达式, 在Python中一个表达式expression是要作为一个结果传送到函数里的,即
>>> print(3 + 4)
7
>>> print('3 + 4')
'3 + 4'
Python打印函数print()详解
本文详细介绍了Python中print()函数的使用方法,包括不同版本的语法差异、参数类型、格式化输出技巧以及如何控制输出行为。适用于初学者和希望深入了解print()功能的开发者。
707

被折叠的 条评论
为什么被折叠?



