2019-05-28python格式化输出
2019-05-28 本文已影响0人
测序九月
因为工作原因,格式化输出更多的是字符串
所以一般就写,用%s
print("hello,%s" % world)
当然不止是print(),包括file.write(), os.system(),好像用到字符串的都可以用,
个人认为,这个应该是str的一个属性。
比如

当然,str属性还有format进行格式化输出,记得format,用大括号{}

python对文本的支持不要太爽,format还是比较好用的
print("hello,{name}".format(**{"name":"jiuyue"})

然后注意!注意!比较容易报错的地方,
1、首先构建字典,键值对是不有没加引号的?
2、字典前面写**,表示以字典传入
3、name不要包含空格,在str中空格也是算字符的
python中还支持模板的建立,核心是string.Template().substitute()
s = string.Template("${name} is ${sex}")
s.substitute(name = 'jinyue',sex = 'boy')
# s.substitute(**{'name':'jinyue','sex':'boy'})
# s.substitute({'name':'jinyue','sex':'boy'})
三个替换方法都是可行的,而format只能用第二个,