Home Backend Development Python Tutorial How to use python's format

How to use python's format

Jul 04, 2019 am 11:21 AM
python

How to use python's format

How to use python’s format?

Python’s format function usage

It enhances the string formatting function. The basic syntax is to replace the previous % with {} and :. The format function can accept unlimited parameters, and the positions do not need to be in order.

**Example 1: The **format function can accept unlimited parameters, and the positions do not need to be in order.

1

2

3

4

5

6

"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序

运行结果:'hello world'

 "{0} {1}".format("hello", "world")  # 设置指定位置

运行结果:'hello world'

"{1} {0} {1}".format("hello", "world")  # 设置指定位置

运行结果:'world hello world'

Copy after login

Example 2: You can also set parameters.

1

2

3

4

5

6

7

8

9

10

11

print("网站名:{name}, 地址 {url}".format(name="Python教程", url="www.py.cn"))

# 通过字典设置参数

site = {"name": "Python教程", "url": "www.py.cn"}

print("网站名:{name}, 地址 {url}".format(**site))

# 通过列表索引设置参数

my_list = ['Python教程', 'www.py.cn']

print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

运行结果:

网站名:Python教程, 地址 www.py.cn

网站名:Python教程, 地址 www.py.cn

网站名:Python教程, 地址 www.py.cn

Copy after login

Example 3: You can also pass in the object to str.format():

1

2

3

4

5

class AssignValue(object):

    def __init__(self, value):

        self.value = value

my_value = AssignValue(6)

print('value 为: {0.value}'.format(my_value))  # "0" 是可选的

Copy after login

The output result is:

1

value 为: 6

Copy after login

Example 4: The following table shows str.format () Multiple methods of formatting numbers

1

2

print("{:.2f}".format(3.1415926));

3.14

Copy after login

Number formatting methods

Number format output description

3.1415926 {:.2f} 3.14 Keep two decimal places

3.1415926 {: .2f} 3.14 Signed to two decimal places

-1 {: .2f} -1.00 Signed to two decimal places

2.71828 {:. 0f} 3 without decimal

5 {:0>2d} 05 Numeric zero padding (padding to the left, width is 2)

5 {:x<4d} 5xxx Numerical padding x (padding Right side, width is 4)

10 {:x<4d} 10xx number complement

##0.25 {:.2%} 25.00% Percent format

1000000000 {:.2e} 1.00e 09 Exponent notation

13 {:10d} 13 Right justified (default , width is 10)

13 {:<10d} 13 left-aligned (width is 10)

13 {:^10d} 13 center-aligned (width is 10)

'{:b}'.format(11) 1011

'{:d}'.format(11) 11

11's base '{:o}'.format (11) 13

'{:x}'.format(11) b

'{:#x}'.format(11) 0xb

'{: #X}'.format(11) 0XB

^, <, > are centered, left-aligned, and right-aligned respectively, followed by width, followed by : and filled with characters, which can only be one character , if not specified, it will be filled with spaces by default.

means displaying before positive numbers and - before negative numbers; (space) means adding spaces before positive numbers

b, d, o, x are binary, decimal, octal, and ten respectively Hexadecimal.

Example 5:

Give you a dictionary:

1

t={‘year’:’2013’,’month’:’9’,’day’:’30’,’hour’:’16’,’minute’:’45’,’second’:’2’}

Copy after login

Please output in this format: 2013-09-30 16:45:02

1

2

3

4

5

6

7

8

9

10

11

12

13

def data_to_str(d):

    &#39;&#39;&#39;

    :param d: 日期字典

    :return: str 格式化后的日期

    &#39;&#39;&#39;

    s1=&#39;{} {:>02} {:>02}&#39;.format(t[&#39;year&#39;],t[&#39;month&#39;],t[&#39;day&#39;])

    s2=&#39;{} {:>02} {:>02}&#39;.format(t[&#39;hour&#39;],t[&#39;minute&#39;],t[&#39;second&#39;])

    print(s1,s2)

    print(&#39;-&#39;.join(s1.split()),end=&#39; &#39;)

    print(&#39;:&#39;.join(s2.split()))

    return 0

t={&#39;year&#39;:&#39;2013&#39;,&#39;month&#39;:&#39;9&#39;,&#39;day&#39;:&#39;30&#39;,&#39;hour&#39;:&#39;16&#39;,&#39;minute&#39;:&#39;45&#39;,&#39;second&#39;:&#39;2&#39;}

print(data_to_str(t))

Copy after login

Run results:

1

2

2013 09 30 16 45 02

2013-09-30 16:45:02

Copy after login
Related recommendations: "

Python Tutorial

"

The above is the detailed content of How to use python's format. For more information, please follow other related articles on the PHP Chinese website!

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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

See all articles