How to Format a String on Python

by Michael Carroll

Python's "string" module contains many useful methods to format strings for presentation to the user. For text strings, several methods manipulate the case, for example capitalization. Other methods add padding to either side of the string to make it fit into a fixed-width field, which is useful for presenting numeric values with different numbers of digits. Padding is stripped away by other methods. The "format" method is a powerful customizable method that combines several of these features, allowing you to precisely control the way numbers are presented as strings.

Basic String Formatting Methods

Launch the Python command-line interpreter. Create a string with the following command: mystring = "this is an example string"

Capitalize the string with the following command: mystring = mystring.capitalize() Type "mystring" to see the changed string in the command-line.

Capitalize each word in the string with the following command: mystring = mystring.title()

Make the whole string uppercase with the following command: mystring = mystring.upper()

Make the whole string lowercase with the following command: mystring = mystring.lower()

Swap the case of each letter in the string with the following command: mystring = mystring.swapcase()

Use the "center," "ljust," and "rjust" methods to justify the string in a fixed-width field. For example, the following command right-justifies the string in a 40-character field: mystring.rjust(40) Add a second argument to one of the justification methods to fill the field with a character. For example, the following command centers the string in a 40-character field, surrounded by asterisks:,'*')

Remove leading and/or trailing characters from the string with the "strip," "lstrip," and "rstrip" methods. For example, type the following two commands: mystring = " spaces around the words " mystring.strip() The string is output without the leading and trailing spaces. The "lstrip" and "rstrip" methods remove only leading or trailing spaces, respectively. To strip off different characters, specify them in the method's argument. For example, try the following two lines: mystring = "" mystring.lstrip('htp:/') Any combination of the characters in the argument are stripped off the beginning of the string, so the "http://" part is not shown in the output.

The "format" Method

Format the result of a math operation with a precision of two decimal places with a command like this: "About {0:.2%} of the population are injured.".format(457/2987) The curly braces indicate the point in the string where the value will be formatted and inserted. The "0" refers to the first argument of the "format" method, the colon begins the format specification, and the ".2%" formatting statement means to use two decimal places, and format the value as a percentage.

Format multiple values by adding arguments to the "format" method: "The result is {0:b} in binary, or {0:d} in decimal. The second result in hexadecimal is {1:x}".format(12*2,2576*432) The first argument is indexed as 0, and the second as 1. The formatting types in this example (binary, decimal, and hexadecimal) are only valid for integers. Consult the python documentation at for a full list of types you can specify.

Preface the format with one of the characters ">," "<," "=," or "^" and a number to align and pad the value in a fixed-width field: "The result is: {:0>20.2f}".format(56/171) Note the omission of the "0" before the colon. "0" is the default value, so for a single argument you do not need it. The "f" format is for fixed point numbers. The "0>20" part causes the value to be right-justified and padded with zeroes in a field of width 20. "=" instead of ">" would cause the padding to come before the sign if there was one, and "^" would center the value in the field.

Cause the sign of the number to always be displayed by using "+" with a numeric format, and use a space to show negatives and add a leading space for positives: "Always show sign: {0:+d} Only show sign if negative, leading space if positive: {0: d}{1: d}".format(56,-67)

Present a number with commas separating every three digits with this command: "{:,}".format(123456789}

Preface binary, octal, or hexadecimal formats with "#" to display an appropriate prefix in the output: "The number {0:,} in hex is: {0:#x}".format(4746379)

Consult the Python documentation at to see more examples of the "format" method.

About the Author

Michael Carroll is a high school mathematics teacher. He has written for various websites since 2010, specializing in programming, web design, electronics and various pieces of software. He holds a bachelor's degree in electrical engineering from the University of Texas, with specialization in embedded system design.