python 基础 字符串格式化

print "hello %s %s" % ('wd','pc')        c风格

print "hello {1} {0}".format("wd",pc')    c#风格      可以定义字符串的顺序
list = ['hello','1','7']
'%s %d-%d'  % ('hello',7,1)
结果 'hello 7-1'

'%s,%s:%s' % (list[0],list[1],list[2])
结果 'hello,1:7'

'%s' %  ','.join(list)
结果  'hello,1,7'

'{0} {1}:{2}'.format('hello','1','7')
结果 'hello 1:7'

'{0} {1}:{2}'.format(*list)
结果 'hello 1:7'

'{} {}:{}'.format('hello','1','7')
'hello 1:7'
dict = {'name':'wd','age':18}
'i am %(name)s,my age is %(age)d' % (dict)
结果 'i am wd,my age is 18'

'i am {name},my age is {age}'.format(**dict)
结果 i am wd,my age is 18
原文地址:https://www.cnblogs.com/guxiaobei/p/7768575.html