文章目录
格式化字符串%号格式化占位符
format格式化(1)位置映射(2)关键字映射(3)元素访问
print()函数查看帮助文件
>>> help(print)
Help on built
-in function
print in module builtins
:
print(...)
print(value
, ..., sep
=' ', end
='\n', file=sys
.stdout
, flush
=False)
Prints the values to a stream
, or to sys
.stdout by default
.
Optional keyword arguments
:
file: a
file-like
object (stream
); defaults to the current sys
.stdout
.
sep
: string inserted between values
, default a space
.
end
: string appended after the last value
, default a newline
.
flush
: whether to forcibly flush the stream
.
语法格式:
print(value
, ...,sep
=' ',end
='\n',file=sys
.stdout
, flush
=False )
等价于:
>>> print(a
,b
,c
,d
)
1 2 3 [4, 5, 6]
>>> print(a
,b
,c
,d
,sep
="$")
1$
2$
3$
[4, 5, 6]
>>> for i
in range(5):
... print(i
, end
=" ")
...
0 1 2 3 4
>>> for i
in range(5):
... print(i
, end
="$")
...
0$
1$
2$
3$
4$
>>> x
=666
>>> import sys
>>> sys
.stdout
.write
(str(x
))
6663
>>> a
,b
,c
,*d
= 1,2,3,4,5,6
>>> d
[4, 5, 6]
格式化字符串
%号格式化
占位符
格式描述
%d有符号的整数%s字符串%c字符及ASCII码%o无符号八进制%x无符号十六进制%X无符号十六进制%e/%E科学技术法,浮点数%f浮点数
% 格式化字符串 用%匹配参数
a
= 100
print("%d%%" % a
)
name
= "Tom"
age
= 18
print("His name is %s, his age is %d." % (name
, age
))
print("His name is", name
, ", his age is", age
, ".")
print("His name is" + name
+ ", his age is" + str(age
) + ".")
format格式化
(1)位置映射
print("{}:{}".format("tom", 18))
tom
:18
print("name:{},age:{}".format("tom", 18))
name
:tom
,age
:18
(2)关键字映射
print("name:{},age:{},{address}".format("tom", 18, address
= "杭州"))
name
:tom
,age
:18,杭州
(3)元素访问
print("第一个元素是
:{0[0]} , 第二个元素是
{0[1]}, 第三个元素是
{0[2]}, 第四个元素是
{1[0]},\
第五个元素是
{1[1]}, 第六个元素是
{1[2]} "
.format(('www.', 'google.', 'com'), ('www.', 'baidu.', 'com.')))
第一个元素是
:www
. , 第二个元素是google
., 第三个元素是com
, 第四个元素是www
., 第五个元素是baidu
., 第六个元素是com
.
%格式化和format格式化,字符串对齐