利用 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)")
原文:https://www.cnblogs.com/joetan/p/10787824.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!