O'Reilly logo

Python in a Nutshell by Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

String Formatting

In Python, a string-formatting expression has the syntax:

               format % values

where format is a plain or Unicode string containing format specifiers and values is any single object or a collection of objects in a tuple or dictionary. Python’s string-formatting operator has roughly the same set of features as the C language’s printf and operates in a similar way. Each format specifier is a substring of format that starts with a percent sign (%) and ends with one of the conversion characters shown in Table 9-1.

Table 9-1. String-formatting conversion characters

Character

Output format

Notes

d, i

Signed decimal integer

Value must be number

u

Unsigned decimal integer

Value must be number

o

Unsigned octal integer

Value must be number

x

Unsigned hexadecimal integer (lowercase letters)

Value must be number

X

Unsigned hexadecimal integer (uppercase letters)

Value must be number

e

Floating-point value in exponential form (lowercase e for exponent)

Value must be number

E

Floating-point value in exponential form (uppercase E for exponent)

Value must be number

f, F

Floating-point value in decimal form

Value must be number

g, G

Like e or E when exp is greater than 4 or less than the precision; otherwise like f or F

exp is the exponent of the number being converted

c

Single character

Value can be integer or single-character string

r

String

Converts any value with repr

s

String

Converts any value with str

%

Literal % character

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required