一.基本的输出方式
1.用加号连接字符串
a = 'This is a'
b = 'python program'
print(a + b )
输出:This is apython program
用加号连接时,两个字符串之间无缝衔接。
注意:‘+’只能用于连接字符串和字符串,不能用于连接字符串和数字。
a = 'This is a'
b = 78
print(a + b )
运行结果:
2.用逗号隔开的输出
a = 'This is a'
b = 'python program'
print(a, b )
输出:This is a python program
可以看出,用逗号隔开输出时,两个字符串之间会自动添加一个空格。
3.控制输出值之间之后的格式
a = 'This is a'
b = 'python program'
c = 'not a C++ resource'
print(a, b, c, sep='#')
输出:This is a#python program#not a C++ resource
sep是用来控制输出字符串之间的值。
a = 'This is a'
b = 'python program'
c = 'not a C++ resource'
d = 'ccc'
print(a, b, c, sep = '#' )
print(d)
输出:This is a#python program#not a C++ resource
ccc默认输出完一次后换行。
a = 'This is a'
b = 'python program'
c = 'not a C++ resource'
d = 'ccc'
print(a, b, c, sep = '#',end ='///' )
print(d)
输出:This is a#python program#not a C++ resource///ccc
用end='///'后,可以看出输出完一次后不换行,而是在后面加入了‘///’。
二.使用占位符
%s :代替字符或字符串
#程序1
a = 'This is a'
print('%s computer'%a)
#程序2
b = 'Bob'
c = 'cumt'
print('我的名字是%s,我来自%s'%(b,c))
程序1输出:This is a computer
程序2输出:我的名字是Bob,我来自cumt
%d:代替整形数字
a = 'Bob'
b = 24
print('我的名字是%s,我的年龄是%d岁'%(a,b))
输出:我的名字是Bob,我的年龄是24岁
%f:浮点数的精确位数输出
a = 'Bob'
b = 24.123
print('我的名字是%s,我的年龄是%.2f岁'%(a,b))
输出:我的名字是Bob,我的年龄是24.12岁
%.1f:保留一位小数位;%.2f:保留2位小数位;........依此类推,%.df:保留d位小数位(均是四舍五入)
三.format输出
#程序1
a = 'Bob'
b = 24
c = '程序员'
print('我的名字是{},我的年龄是{}岁,我的工作是{}'.format(a,b,c))
#程序2
a = 'Bob'
b = 24
c = '程序员'
print('我的名字是{2},我的年龄是{1}岁,我的工作是{0}'.format(c,b,a))
输出结果都为:我的名字是Bob,我的年龄是24岁,我的工作是程序员
使用format可以代替任意的数值或字符串,还可以对值的键入顺序编号。