SoFunction
Updated on 2024-11-10

Python's formatted output (format,%) example in detail

Imperial City PK

Formatting strings in Python currently has two camps: % and format, which one should we choose?

Since Python 2.6 introduced format as a way to format strings, I don't think % or format is even a question. Look down the page if you don't believe me.

# Define a coordinate value
c = (250, 250)
# Use % to format
s1 = "Enemy coordinates: %s" % c

The above code will obviously throw a TypeError as follows:

TypeError: not all arguments converted during string formatting

Formatting requirements like these we need to write in the ugly format below to make it work:

# Define a coordinate value
c = (250, 250)
# Use % ugly formatting...
s1 = "Enemy coordinates: %s" % (c,)

The above problem does not exist with format:

# Define a coordinate value
c = (250, 250)
# Formatting with format
s2 = "Enemy coordinates:{}".format(c)

Obviously, this one reason above is enough for you to use format in future projects.

new feature

f-strings was added in Python 3.6:

In[1]: name = "Q1mi"
In[2]: age = 18
In[3]: f"My name is {name}.I'm {age}"
Out[3]: "My name is 'm 18"

Common Format Usage

By position

In[1]: data = ["Q1mi", 18]
In[2]: "Name:{0}, Age:{1}".format(*data)
Out[2]: 'Name:Q1mi, Age:18'

By keyword

In[1]: data = {"name": "Q1mi", "age": 18}
In[2]: "Name:{name}, Age:{age}".format(**data)
Out[2]: 'Name:Q1mi, Age:18'

Through object properties

In[1]: class Person(object):
  ...:   def __init__(self, name, age):
  ...:      = name
  ...:      = age
  ...:   def __str__(self):   
  ...:     return "This guy is {}, {} years old.".format(self=self)
  ...:   
In[2]: p = Person("Q1mi", 18)
In[3]: str(p)
Out[3]: 'This guy is Q1mi, 18 years old.'

By subscripting

In[1]: "{0[0]} is {0[1]} years old.".format(data)
Out[1]: 'Q1mi is 18 years old.'

Filling and Alignment

Fill is often used with alignment

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

The character with padding after the : sign can only be one character, the default is padded with spaces if not specified.

In[1]: "{:>10}".format('18')
Out[1]: '    18'
In[2]: "{:0>10}".format('18')
Out[2]: '0000000018'
In[3]: "{:A>10}".format('18')
Out[3]: 'AAAAAAAA18

Supplement a string with its own zfill() method:

The Python zfill() method returns a string of the specified length, with the original string right-justified and padded with zeros in front.

zfill() method syntax: (width)

The parameter width specifies the length of the string. The original string is right-aligned and padded with zeros.

Returns a string of the specified length.

In[1]: "18".zfill(10)
Out[1]: '0000000018'

Precision and typef

Precision is often used with type f.

In[1]: "{:.2f}".format(3.1415926)
Out[1]: '3.14'

where .2 denotes a precision of length 2 and f denotes a float type.

Other Binary

The main thing is the binary system. b, d, o, and x are binary, decimal, octal, and hexadecimal, respectively.

In[1]: "{:b}".format(18)
Out[1]: '10010'
In[2]: "{:d}".format(18)
Out[2]: '18'
In[3]: "{:o}".format(18)
Out[3]: '22'
In[4]: "{:x}".format(18)
Out[4]: '12'

thousands separator

In[1]: "{:,}".format(1234567890)
Out[1]: '1,234,567,890'

summarize

The above is a small introduction to python's formatting output (format,%) examples in detail, I hope to help you, if you have any questions please leave me a message, I will promptly reply to you. I would also like to thank you very much for your support of my website!