Using the Format function for formatting strings in Python
Since python2.6, a new function Str.format () that formats the string has been added to the power. So, what's the advantage of being compared to the previous% format string?
Grammar
It replaces% with {} and:.
Map sample
There are 4 ways to implement a value mapping
The first type: where to use
1>>>Print('{0},{1}'. Format ('ABC', 2333) ); 2abc,23333>>>4>>> a='AAA' 5>>> b='BBB' 6 7>>>Print('A={0},b={1}'. Format (A, b));#Using Variables8a=aaa,b=bbb
The second type: using keywords
1>>>Print('{name},{age}'. Format (age=18,name='Zhangsan'));#using Constants2zhangsan,183>>>4 5>>> age=256>>> name='Jone' 7>>>Print('{name},{age}'. Format (age=age,name=name));#cases where variables are used8jone,25
The third type: Using Object properties
1>>>classPerson :2 def __init__(self,name,age):3Self.name =name; 4Self.age =Age ; 5 6 deftostr (self):7 return 'Name Is{self.name} age is {self.age} old'. Format (self=Self ); 8 9 Ten>>> s = person ('Zhangsan', 25). Tostr (); One>>>Print('s=%s'%s); AS=name Iszhangsan Age is 25 Old ->>>
Fourth: Use subscript (list, tuple)
1>>> p=['Zhangsan', 25]#using the list2>>>Print('{0[0]},{0[1]}'. Format (p)); 3zhangsan,254>>>5>>> p= ('Zhangsan', 25,'Beijing');#working with tuples6>>>Print('name={0[0]},age={0[1]} city={0[2]}'. Format (p)); 7Name=zhangsan,age=25 city=beijing
Using the Format function for formatting strings in Python