变量替换的两种方式 Wednesday, July 1, 2015 6:39 AM
hi=’yaung’ ih=’zhou’
print “this is {0}”.format(hi)
this is yaung
print ‘this is %s’ % (hi)
this is yaung
print ‘this is {1} {0}’.format(hi,ih)
this is zhou yaung
print ‘this is %s %s’ % (ih,hi)
this is zhou yaung
可以看出两种方法:
- {n}”.format(xx) 2.%s” % (xx)
如果字符串里面本来就有%字符串,需要对%做转义,这里不能用\转义,而是用%
print ‘i have 100% %s name’ % ‘english’ Traceback (most recent call last): File “ < stdin>”, line 1, in < module> TypeError: not all arguments converted during string formatting print ‘i have 100%% %s name’ % ‘english’ i have 100% english name 或者用fomat格式避免 print ‘i have 100% {0} name’.format(‘english’) i have 100% english name
已使用 Microsoft OneNote 2016 创建。