Python's powerful string formatting function - format
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'
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'
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
By subscript
>>> '{0[1]}.{0[0]}.{1}'.format(['pyhtontab', 'www'], 'com') 'www.pyhtontab.com'
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:
>>> '{:>10}'.format(2016) ' 2016' >>> '{:#>10}'.format(2016) '######2016' >>> '{:0>10}'.format(2016) '0000002016'
Number Precision and type f
Precision is often used together with type f
>>> '{:.2f}'.format(2016.0721) '2016.07'
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.
>>> '{:b}'.format(2016) '11111100000' >>> '{:d}'.format(2016) '2016' >>> '{:o}'.format(2016) '3740' >>> '{:x}'.format(2016) '7e0' >>>
Used, the number can also be used as the thousands separator for the amount.
>>> '{:,}'.format(20160721) '20,160,721'
The function of format is too powerful, and there are many functions. You can try it.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

The article discusses the role of virtual environments in Python, focusing on managing project dependencies and avoiding conflicts. It details their creation, activation, and benefits in improving project management and reducing dependency issues.
