首页 > 编程语言 > 详细

Python基础:十二、格式化输出print() , input()

时间:2019-05-02 13:32:26      阅读:132      评论:0      收藏:0      [点我收藏+]

利用 print() 进行格式化输出

在print()的结尾,python解释器会自动添加换行符,可以通过在print中加上end="内容"将换行符替换为end后的内容(内容可以为空)

print("你好",end="吗?")
print("今天天气不错")
#输出结果为:你好吗?今天天气不错

转义字符:\

换行:\n

print(a,b,c)
#输出结果会为:a b c  中间有空格隔开
#print()对空格敏感
print(this is an nice day,the weather is sunny,and the temperature is 15 centigrade)

 格式化输出

第一种写法:加法太多,会导致内存耗费太多(每次加法其实都会产生一个新的字符串)

print("this is a" + condition + "day , theweather is" + weather + "and the temperature is" + temperature 

第二种写法:占位符写法

%s 字符串的占位符,但也可以放置任何内容

在末尾放上%(),括号内的内容是需要放的字符串或数字,按安放顺序排列,%后的小括号可写可不写,%前最好加一个空格

print("this is a %s day , the weather is %s , and the temperature is %s " %( condition , weather , temperature))

 %d数字的占位符

age=input("How old are you?")
age=int(age)
print("His age is %d" %(age))

 如果字符串中有了占位符,那么后面的所有%都是占位,需要转义

但如果没有占位符,百分号还是百分号

condition="cloudy"
print("%s is just 20% in a year" %(condition))   #错误写法,因为在20%前已经有了占位符,此处的%需要转义
print("cloudy is just 20% in a year")   #此时因为没有占位符,百分号是正常的,不需要转义
print("%s is just 20 %% in a year " %(condition))   #在需要转义的%号前再加一个%,即写为20%%可完成转义

利用 input() 格式化输出

#例:询问天气
condition=input("How‘s today")
weather=input("what‘s the weather today?")
temperature=input("what‘s the temperature today?(incentigrade)")

Python基础:十二、格式化输出print() , input()

原文:https://www.cnblogs.com/joetan/p/10787824.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!