String formatting of the Python base

Source: Internet
Author: User

There are two types of string formatting in Python, one is%, and the other is the format () function in Str.

%

List format characters

%s string

%c single character

%b binary integers

%d decimal integers

%i Decimal Integer

%o Eight-binary integers

%x hexadecimal integer

%e index (base written as E)

%E index (base written as E)

%f floating Point

%F floating-point number, same as above

%g index (e) or floating point number (depending on display length)

Percent% character "%"

Example:

#today there is a format characterName='Dahuang'Print('%s is my dog'%name)#The result is:Dahuang ismy dog#when you have two or more than two format characters, pass multiple values to the template with a tupleName='Dahuang'obj='Dog'Print('%s is my%s'%(name,obj))#Results:Dahuang ismy dog#we can name the format character in a dictionaryPrint("I ' m% (name) s. I ' m% (age) D- old"% {'name':'Dahuang',' Age': 6})#Results:I'm Dahuang. I'M 6 Old

Format ()

Format () replaces% with {}

Within {} You can

By location Mapping:

#0,1 for position>>>'{0},{1}'. Format ('KKK', 123)  'kkk,123'#default formatting according to order>>>'{},{}'. Format ('KKK', 123)'kkk,123'>>>'{1},{0}'. Format ('KKK', 123) '123,KKK'

by keyword mapping:

>>>'{name},{age}'. Format (age=15,name='liming' )'liming,15'

by subscript:

>>> li=['liming','xiaohong']' {0[0]},{0[1]} ' . Format (LI) ' Liming,xiaohong '

String formatting of the Python base

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.