python字符串格式化方法之%s和format函数用法与区别

上一篇 / 下一篇  2018-03-29 11:16:43 / 个人分类:python


一、%s用法(%s的用法是写多少个,后面就要传多少个)
例1:
>>> "my name is %s and I am %d years old" %("xiaoming",18)
'my name is xiaoming and I am 18 years old'
例2:
>>> "format test %s %s %s" % ('abc','abc','abc')
'format test abc abc abc'

二、format用法(基本语法是通过{}和:来代替%。format函数可以接受不限个参数,位置可以不按顺序)
例3:#设置指定位置,按默认顺序
>>> "{} {}".format("hello","world")
'hello world'
例4:# 设置指定位置
>>> "{0} {1}".format("hello", "world")
'hello world'
例5:# 设置指定位置
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'
例6:# 一个num变量可以接受不限个参数(可以例2对比)
>>> "format test {num} {num} {num}".format(num="abc")
'format test abc abc abc'




p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 16.0px 'Andale Mono'; color: #28fe14; background-color: #000000; background-color: rgba(0, 0, 0, 0.9)} span.s1 {font-variant-ligatures: no-common-ligatures}

TAG:

 

评分:0

我来说两句

Open Toolbar