Python: Format String

By Xah Lee. Date: . Last updated: .

Convert into string format.

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

# python 3

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')]

C Style printf

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

print "…" % (arg1, arg2, …)

# python 3

# 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, …).

Inside the string, use {} as placeholder. Inside {…} is specification for the format.

# python 3

print("{}".format("cat"))
# cat

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

Use {{}} to include literal {}

# python 3

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

Format Codes

# python 3

# “: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:

# python 3

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

Change Print Argument Order

# python 3

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

Print Without Newline

# python 3
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

  1. Quote String
  2. String Methods
  3. Format String

If you have a question, put $5 at patreon and message me.

Python

  1. Python 3 Basics
  2. Python 2 Basics
  3. Python 2 and 3 Difference
  4. Print Version
  5. Builtin Help
  6. Quote String
  7. String Methods
  8. Format String
  9. Operators
  10. Complex Numbers
  11. True, False
  12. if then else
  13. Loop
  14. List Basics
  15. Loop Thru List
  16. Map f to List
  17. Copy Nested List
  18. List Comprehension
  19. List Methods
  20. Sort
  21. Dictionary
  22. Loop Thru Dict
  23. Dict Methods
  24. Tuple
  25. Sets
  26. Function
  27. Closure
  28. 2 Closure
  29. Decorator
  30. Class
  31. Object, ID, Type
  32. List Modules
  33. Write a Module
  34. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. File Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency

Web

  1. Send Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Append String in Loop
  7. Timing f timeit
  8. Keyword Arg Default Value Unstable
  9. Check Page Load Size
  10. Thumbnail Generation