Fundamentals 4 min read

Using Python's str.format() for Advanced String Formatting

This article explains Python's str.format() method introduced in Python 2.6, covering its basic syntax, positional and named arguments, object formatting, numeric formatting options, alignment, fill characters, type specifiers, brace escaping, and custom template usage with clear code examples.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using Python's str.format() for Advanced String Formatting

Python 2.6 introduced the str.format() function, which expands the capabilities of string formatting by replacing the older % operator with a more flexible syntax using {} and optional : specifiers.

Basic usage allows unlimited arguments and positional reordering, for example:

>>> "{} {}".format("hello", "world")  # 'hello world'
>>> "{0} {1}".format("hello", "world")  # 'hello world'
>>> "{1} {0} {1}".format("hello", "world")  # 'world hello world'

Named arguments can be supplied directly or via a dictionary:

print("网站名:{name}, 地址 {url}".format(name="测试天下", url="www.testtx.com"))
site = {"name": "测试天下", "url": "www.testtx.com"}
print("网站名:{name}, 地址 {url}".format(**site))

Lists can be referenced by index, and objects by attribute:

my_list = ["测试天下", "www.testtx.com"]
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))

class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value))

Numeric formatting supports precision, alignment, fill characters, sign handling, and type specifiers (binary, decimal, octal, hexadecimal). For example:

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

Alignment and fill are specified with ^ (center), < (left), > (right) followed by a width and an optional single‑character fill:

print("{:<10}".format("left"))   # left padded with spaces
print("{:*^10}".format("center")) # centered padded with '*'

Sign options + and a leading space can force display of positive signs or a leading space for positive numbers.

Braces can be escaped by doubling them:

print("{} 对应的位置是 {{0}}".format("testxt"))  # testxt对应的位置是{0}

A reusable template can be defined and formatted later, as shown:

tplt = "{:2}\t{:8}\t{:<16}"
print(tplt.format("序号", "价格", "商品名称"))

These examples demonstrate the versatility of str.format() for constructing dynamic strings in Python.

Code ExampleString Formattingformat-specifiersstr.format
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.