在python3中,使用print有不同的形式,总结如下:
1. print(str1, str2, str3…)或print(str1+str2+str3…) 这是最简单的一种输出方式,也比较容易理解,这样的输出形式得到的结果会是由str1、str2、str3…拼接成的一个长字符串。两者的不同之处如下:
str_1 = 'today is'
str_2 = 'a good day.'
str_3 = 'I am very happy!'
#输出:today is a good day. I am very happy!(各字符串之间有空格)
print(str_1, str_2, str_3)
#输出:today isa good day.I am very happy!(各字符串之间无空格)
print(str_1 + str_2 + str_3)
2. format() 一种比较常见的格式化输出方式。其格式为:
print('{要输出的内容将在此处显示}'.format(要输出的内容))
# 输出:Alice and Zoey are good friends.
print('{} and {} are good friends.'.format('Alice', 'Zoey'))
# 在括号中的数字用于指向传入对象在 format()中的位置
# 输出:Zoey and Alice are good friends.
print('{1} and {0} are good friends.'.format('Alice', 'Zoey'))
# format() 可以使用关键字参数
# 输出:Bob and Tina are couples.
print('{boy} and {girl} are couples.'.format(boy='Bob', girl='Tina'))
# 格式化输出
# 1.!a——使用ascii函数(判断参数是不是在ASCII码表中)
char = '哈哈哈'
# 输出:转换后的结果是:'\u54c8\u54c8\u54c8'
print('转换后的结果是:{!a}'.format(char))
# 2.!s——使用str
num = 123
# 报错:此时num为int型
print(num + ',hello')
# 不会报错,输出:123,hello
print('{!s}'.format(num) + ',hello')
# 3.':.Nf'——保留N位小数
float_num = 1.234567
# 输出:保留三位小数的结果是:1.235
print('保留三位小数的结果是:{:.3f}'.format(float_num))
format的更多用法见(https://blog.csdn.net/weixin_30480651/article/details/99312020)
3. % %是一种比较旧的输出方式,使用%占位,在%后的内容用于填充,具体用法如下:
# 使用%s输出字符串:Nicky is learning music.
print('%s is learning %s.' % ('Nicky', 'music'))
# 使用%d输出整数:The number is 54.
num = 54
print('The number is %d.' % num)
# 使用%.Nf输出N位小数:The value is rounded to three decimal places is 2.444.
float_num = 2.444444
print('The value is rounded to three decimal places is %.3f.' % float_num)
|