>>> 'growth rate: %d %%' % 7
'growth rate: 7 %'
尝试使用其他方法对%进行转义,但是好像没有用,有什么其他方法欢迎评论。
2、使用format 方法进行格式化
代码演示:
age = 25
name = 'Swaroop'
print('{0} is {1} years old'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
位置使用{1}按照使用的顺序写好,后面格式使用 .format() 写好对应的参数即可。
输出结果:
Swaroop is 25 years old
Why is Swaroop playing with that python?
其实也可以使用第一种方法实现:
age = 25
name = 'Swaroop'
print('%s is %s years old'%(name, age))
print('Why is %s playing with that python?'%(name))
输出
Swaroop is 25 years old
Why is Swaroop playing with that python?
实现的结果都是一样的。
总结
以上就是本文关于python中使用%与.format格式化文本方法解析的全部内容,希望对大家有所帮助。