Python: Format String

By Xah Lee. Date: . Last updated: .

Convert into string format.

repr()
Convert a data into a string form that can be read back into Python or for eval()
str()
Convert into a string in a human readable form.

Note: in practice, these two returns the same thing.

ss = [3, 4, 3.123456789012345678901234567890, (7, 8, "9")]
print (str(ss))    # [3, 4, 3.1234567890123457, (7, 8, '9')]
print (repr(ss))   # [3, 4, 3.1234567890123457, (7, 8, '9')]

printf

The “print” function supports string formatting in the style of C's printf. The syntax is:

print str % (arg1, arg2 etc)

# integer
print("[%d]" % (1234))
# [1234]

# padding by space
print("[%4d]" % (12))
# [  12]

# float. 2 integer, 4 decimal
print("[%2.4f]" % (3.123456789))
# [3.1235]

# string
print("[%5s]" % ("cats"))
# [ cats]

print("[%2s]" % ("cats"))
# [cats]

print("[%2d] [%6d] [%2.4f] [%s]" % (1234, 5678, 3.123456789, 'cats!'))
# [1234] [  5678] [3.1235] [cats!]

‹string›.format(…)

A more flexible way to format string is

str.format(arg1, arg2 etc).

Inside the string, use {spec} as placeholder. spec is specification for the format, can be empty.

print("{} cats {} dogs.".format(3,4))
# 3 cats 4 dogs.

Use {{}} to include literal {}

# use {{}} to include literal {}
print("brace {{}}, a is {}".format(3))
# brace {}, a is 3

Format Codes

# “:s” is for string
print("{:s}".format("cat"))
# cat

# decimal int
print("{:d}".format(3))
# 3

# binary
print("{:b}".format(3))
# 11

# hex
print("{:x}".format(10))
# a

# list
print("{:}".format([7, 8]))

Format number in human readable format:

print("{:,}".format(78515573)) # 78,515,573

Change Print Argument Order

print("{1:}, {0:}".format(3, 4))
# 4, 3

Print Without Newline

print( "a", "b", sep=",", end=",")
print( "c")
# prints
# a,b,c

Python 2, Print Without Newline

To print without the newline char added at the end, add a comma.

# -*- coding: utf-8 -*-
# python 2

# suppress printing newline
print "rabbit",
print "tiger"

# prints
# rabbit tiger

Or, use sys.stdout.write().

# -*- coding: utf-8 -*-
# python 2

import sys
sys.stdout.write("rabbit")
sys.stdout.write("tiger")

# prints
# rabbittiger

Thanks to Yuri Khan for a suggetion on Python print.

Python String

Python

Overview

Help

Comment

String

Arithmetic

Boolean

Conditional

Loop

Data Structure

Function and Class

Module

Misc

Regex

Text Processing

Web

Misc