search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Python String | format method

schedule Aug 10, 2023
Last updated
local_offer
Python
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Python's str.format(~) method returns a formatted string with provided argument values inserted in place of placeholders within the source string.

Parameters

2 types of parameters:

Type

Description

Positional

Specify the position of the element to replace

Keyword

Specify key = value for replacing {key} within source string

Return value

Returns the formatted string.

Examples

Positional parameter

To specify placeholders {} with the numeric index of positional arguments to format the string with:

x = 'Meet {0}. {0} is {1} years old.'
x.format("Sky", 24)
'Meet Sky. Sky is 24 years old.'

"Sky" is provided as first argument (i.e.index position 0), hence it is inserted at occurrences of {0} in the source string. As 24 is provided as the second argument (i.e. index position 1), it is inserted at {1} in the source string.

Keyword parameter

To insert "Sky", "Towner" and 24 in place of the {fname:<}, {lname} and {age} placeholders respectively:

y = 'My name is {fname:<} {lname}. I am {age}.'
y.format(fname="Sky", lname="Towner", age=24)
'My name is Sky Towner. I am 24.'

Note that we provide a formatting type :< for {fname} which will left-align the string within the available space.

Formatting output

To format the value provided as population with thousands separator:

z = 'The population of this town is {population:,}.'
z.format(population=1200000))
The population of this town is 1,200,000.

By providing :, formatting type, the population value 1200000 is formatted with comma thousands separator in the return string.

List of formatting types

Alignment options

Option

Meaning

:<

Forces the field to be left-aligned within the available space.

:>

Forces the field to be right-aligned within the available space.

:=

Forces the padding to be placed after the sign (if any) but before the digits.

:^

Forces the field to be centered within the available space.

Sign options

Option

Meaning

:+

Indicates that a sign should be used for both positive as well as negative numbers.

:-

Indicates that a sign should be used only for negative numbers (this is the default behavior).

space

Indicates that a leading space should be used on positive numbers, and a minus sign on negative numbers.

String presentation

Type

Meaning

:s

String format. This is the default type for strings and may be omitted.

None

The same as ':s'.

Integer presentation

Type

Meaning

:b

Binary format. Outputs the number in base 2.

:c

Character. Converts the integer to the corresponding unicode character before printing.

:d

Decimal Integer. Outputs the number in base 10.

:o

Octal format. Outputs the number in base 8.

:x

Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9.

:X

Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9.

:n

Number. This is the same as ':d', except that it uses the current locale setting to insert the appropriate number separator characters.

None

The same as ':d'.

Floating point and decimal presentation

Type

Meaning

:e

Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent. The default precision is 6.

:E

Exponent notation. Same as 'e' except it uses an upper case ‘E’ as the separator character.

:f

Fixed-point notation. Displays the number as a fixed-point number. The default precision is 6.

:F

Fixed-point notation. Same as 'f', but converts nan to NAN and inf to INF.

:g

General format.

:G

General format. Same as 'g' except switches to 'E' if the number gets too large. The representations of infinity and NaN are uppercased, too.

:n

Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters.

:%

Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percentage sign.

:_

Underscore as a thousands separator.

:,

Comma as a thousand separator.

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...