Home Backend Development Python Tutorial Python's powerful string formatting function - format

Python's powerful string formatting function - format

Oct 17, 2016 am 11:38 AM

Since python2.6, a new function str.format() for formatting strings has been added, which is very powerful. So, what advantages does it have compared with the previous % formatted string? Let's unveil its shyness.

Syntax

It uses {} and: instead of %


Positional method formatting

>>> '{}.{}'.format('pythontab', 'com')
'pythontab.com'
>>> '{}.{}.{}'.format('www', 'pythontab', 'com')
'www.pythontab.com'
>>> '{1}.{2}'.format('www', 'pythontab', 'com')
'pythontab.com'
>>> '{1}.{2} | {0}.{1}.{2}'.format('www', 'pythontab', 'com')
'pythontab.com | www.pythontab.com'
Copy after login

The format function of the string can accept unlimited parameters, the parameter positions can be out of order, and the parameters can not be used or Used multiple times, very flexible

Note: It cannot be empty {} under python2.6, but it can be used in python2.7 or above.


By keyword parameters

>>> '{domain}, {year}'.format(domain='www.pythontab.com', year=2016)
'www.pythontab.com, 2016'
>>> '{domain} ### {year}'.format(domain='www.pythontab.com', year=2016)
'www.pythontab.com ### 2016'
>>> '{domain} ### {year}'.format(year=2016,domain='www.pythontab.com')
'www.pythontab.com ### 2016'
Copy after login

By object properties

>>> class website: 
        def __init__(self,name,type): 
            self.name,self.type = name,type 
        def __str__(self): 
          return 'Website name: {self.name}, Website type: {self.type} '.format(self=self) 
>>> print str(website('pythontab.com', 'python'))
Website name: pythontab.com, Website type: python
>>> print website('pythontab.com', 'python')
Website name: pythontab.com, Website type: python
Copy after login

By subscript

>>> '{0[1]}.{0[0]}.{1}'.format(['pyhtontab', 'www'], 'com')
'www.pyhtontab.com'
Copy after login

With these convenient "mapping" methods, we have a lazy tool. Basic python knowledge tells us that lists and tuples can be "broken" into ordinary parameters for functions, while dict can be broken into keyword parameters for functions (through and *). So you can easily pass a list/tuple/dict to the format function, which is very flexible.


Format qualifiers

It has a wealth of "format qualifiers" (the syntax is {} with a symbol in it), such as:

Padding and alignment

Padding is often used together with alignment

^, <、>They are centered, left-aligned and right-aligned respectively, followed by width

: The padding character after the sign can only be one character. If not specified, the default is to fill it with spaces


Code example:

>>> &#39;{:>10}&#39;.format(2016)
&#39;      2016&#39;
>>> &#39;{:#>10}&#39;.format(2016)
&#39;######2016&#39;
>>> &#39;{:0>10}&#39;.format(2016)
&#39;0000002016&#39;
Copy after login

Number Precision and type f

Precision is often used together with type f

>>> &#39;{:.2f}&#39;.format(2016.0721)
&#39;2016.07&#39;
Copy after login

Where. 2 represents the precision of length 2, and f represents the float type.

Other types

are mainly based on base. b, d, o, and x are binary, decimal, octal, and hexadecimal respectively.

>>> &#39;{:b}&#39;.format(2016)
&#39;11111100000&#39;
>>> &#39;{:d}&#39;.format(2016)
&#39;2016&#39;
>>> &#39;{:o}&#39;.format(2016)
&#39;3740&#39;
>>> &#39;{:x}&#39;.format(2016)
&#39;7e0&#39;
>>>
Copy after login

Used, the number can also be used as the thousands separator for the amount.

>>> &#39;{:,}&#39;.format(20160721)
&#39;20,160,721&#39;
Copy after login

The function of format is too powerful, and there are many functions. You can try it.


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

What is the reason why pipeline files cannot be written when using Scapy crawler? What is the reason why pipeline files cannot be written when using Scapy crawler? Apr 02, 2025 am 06:45 AM

Discussion on the reasons why pipeline files cannot be written when using Scapy crawlers When learning and using Scapy crawlers for persistent data storage, you may encounter pipeline files...

See all articles