字符串的格式化输出
练习代码://download.youkuaiyun.com/download/SY1996922/12005538
字符串 表示 ’ ‘单引号; " "双引号; ‘’’ ‘’'三引号(可保留格式输出,可作为注释使用);
#常量 Java中final标识符表示常量,Python中名字是大写就认为是常量
NAME = 'JACK'
print(NAME)
print('hello')#输出的是字符串
print('''你好
我好
大家好''')#长字符串保持原格式输出
person = '易烊千玺'
address = '青岛市崂山区松岭路'
phone = '19563247841'
num = 15
print('订单的收件人是:'+person+'收货地址是:'+address+'联系方式:'+phone)
print('订单的收件人是:'+person+',收货地址是:'+address+',联系方式:'+phone+'数量是:'+num)
print('数量是:'+str(num))
‘+’ 符号表示拼接,字符串+字符串 的形式可以,但是字符串+int就会报一个typeerror错误
str(int)------把int转成str,强制类型准换
1.使用占位符 %s ; %d(digit)整型;%f(float)
print('订单的收件人是:%s,收货地址是:%s,联系方式:%s,数量是:%d'%(person,address,phone,num))
%f, %.0f , %.1f ……
salary = 9996.325
print('薪水:%.1f'%salary)
print('薪水:%.2f'%salary)
print('薪水:%.3f'%salary)#小数点后保留几位输出,结果四舍五入
运行结果:
练习:
movie = '大侦探'
ticket = 45.9
count = 32
total = ticket * count
#写法1
message = '''
电影:%s
人数:%d
单价:%f
总票价:%.1f
''' % (movie,count,ticket,total)
#写法2
print(message)
print('电影:%s' % movie)
print('人数:%d' % count)
print('单价:%.0f' % ticket)
print('总票价:%.1f' % total )
运行结果:
2.使用format
age = 2
detail = 'I\'m {} years old '.format(age)
print(detail)
#foramt 是字符串中的一个函数,只有字符串才能调用formate()
sex = 'boy'
detail1 = 'I\'m {} years old ,I\'m a {}!'.format(age,sex)#注意要一一对应!!!
print(detail1)
运行结果: