【format】 vs 【%】 in Python
相比【%】,Python中的【format】更显精致,对于【%】来说,它无法同时传递一个变量和元组(Tuple)
比如,对于:
“hi there %s” % name
如果name传递Tuple元组类型参数,那么将抛出如下错误:
TypeError: not all arguments converted during string formatting
为保证其正常执行,你需要这么做,确保参数name为只包含单个元素的元组:
“hi there %s” % (name,) # supply the single argument as a single-item tuple
def format_with_format(obj):
try:
return 'hello {name}'.format(name=obj)
except Exception as e:
print(e)
return 'format_with_format error'
def format_with_percent(obj):
try:
return 'hello %s' % obj
except Exception as e:
print(e)
return 'format_with_percent error'
def format_with_percent_optimization(obj):
try:
return 'hello %s' % (obj,)
except Exception as e:
print(e)
return 'format_with_percent error'
if __name__ == '__main__':
L = [1, 2, 3]
T = (1, 2, 3, 4)
print(format_with_format(L))
print(format_with_format(T))
print(format_with_percent(L))
print(format_with_percent(T))
print(format_with_percent_optimization(T))
https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format
还没有评论,来说两句吧...