Home arrow Python arrow Page 2 - Python 3.1: String Formatting

Try It Out: More String Formatting - Python

In this conclusion to a three-part series on Python 3.1, you'll learn how to format strings and put them together in different ways. We'll also review what we covered in the series as a whole, which includes your first Python program. This article is excerpted from the book Beginning Python: Using Python 2.6 and Python 3.1,, written by James Payne, Developer Shed Editor-in-Chief (Wrox, 2010; ISBN: 0470414634).

  1. Python 3.1: String Formatting
  2. Try It Out: More String Formatting
  3. Summary
By: James Payne
Rating: starstarstarstarstar / 3
May 12, 2010

print this article



In this example, you tell the format specifier how many characters to expect. Try the following code and watch what happens:

> > > “%s %s %10s” % (“John” , “Every”, “Man”)

‘John Every Man’

> > > “%-5s %s %10s” % (“John” , “Every”, “Man”)

John Every Man

How It Works

In the first line of code, the word Man appears far away from the other words; this is because in your last format specifier, you added a 10, so it is expecting a string with ten characters. When it does not find ten (it only finds three . . . M - a - n) it pads space in between with seven spaces.

In the second line of code you entered, you will notice that the word Every is spaced differently. This occurs for the same reason as before — only this time, it occurred to the left, instead of the right.

Whenever you right a negative ( – ) in your format specifier, the format occurs to the left of the word. If there is just a number with no negative, it occurs to the right.

>>> More Python Articles          >>> More By James Payne

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates


Dev Shed Tutorial Topics: