Using the Format function for formatting strings in Python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.