Page 1 of 1

Python Basics: String Formatting

Posted: Mon Dec 22, 2014 4:03 pm
by comathi
Hey guys! A while back, I wrote this tutorial on Python Strings, but I didn't go into detail about some of the great functions Python offers for Strings.

Perhaps the most notable one of them all is String formatting, which allows you to control how a String will be displayed in the console. This is what we're going to focus on in this tutorial.

The str.format() method
There are a couple of ways to format Strings in Python, but the best (in my opinion) is by using the str.format() method, which allows you to specify and reuse fields for the data you want to format. Let's see how it works:
Code: Select all
"{0} is a great programming forum, it currently has {1} members".format("Codenstuff", 4952)
This will output "Codenstuff is a great programming forum, it currently has 4952 members"

As you can see, Strings are formatted by calling the format() method on a String literal. To insert data into the String, all you have to do is put a field name between curly braces ({}). In the example above, an integer is used. This corresponds to the index of the parameter given to format(). However, it's also possible to give actual names to our fields, like so:
Code: Select all
"{sitename} is a great programming forum, it currently has {members} members".format(sitename="Codenstuff", members=4952)
This will output the same thing as the previous example, but it uses named fields instead of indexes, which means the parameters given to format() don't have to be in any specific order.

As I said earlier, the beauty of fields is that they can be reused, let's look at an example of that:
Code: Select all
"Do you know {person}, {person}, {person}. Do you know {person} who lives {place}".format(person="the Muffin Man", place="on Drury Lane")
You can probably guess the output of the above code ;)

You've also probably noticed that the parameters passed to format() don't have to be a String. In fact, they can be Strings, numbers, dictionaries, lists.... anything really, as long as they can be accessed:
Code: Select all
languages = ["VB.NET", "Java", "Python", "C++"]

"{0[0]}, {0[1]}, {0[2]} and {0[3]} are all programming languages".format(languages)
In the above code, a list was passed to the format() method, but because its elements can be individually accessed, the code remains valid :)

Format specifiers
Along with the field names, it's also possible to tell Python how we want the data to be represented... That's the point of String formatting, after all.

Format specifiers come after the field name and are seperated from the field name with a colon (:). All specifiers are optional, but if you choose to declare them, here's the order in which it must be done:
  • Fill
  • Align
  • Sign
  • #
  • 0
  • Width
  • ,
  • .precision
Fill is any character except "}" that will be used to fill in the space before the data (if it occupies less space than the minimum width).

Align specifies the data alignment: < for left, > for right and ^ for center

Sign: + forces the sign to be displayed, - only displays the sign when needed and " " displays - or a blank space accordingly.

# forces Python to display the type of data (for integers): 0b, 0o, 0x

0 forces Python to zero-pad numbers (insert zeroes in front of the number if it is smaller than the field width)

width is the minimum width of the data field

, tells Python to group numbers with commas

.precision is the maximum width of the data field (for Strings) or the maximum precision to be displayed (for numbers).

Here are a few examples:
Code: Select all
"This account contains {0:10.2f}$".format(56452.45421)
Will output 'This account contains 56452.45$'
Code: Select all
"You have ticket number {0:05d}".format(20)
Will output 'You have ticket number 00020'

That's it for this tutorial guys! It's been a while since I've posted, but I really hope these are useful to you cooll;

Re: Python Basics: String Formatting

Posted: Mon Dec 22, 2014 4:39 pm
by SumCode
Also, if I remember correctly, you can format strings using '%s'. So like this
Code: Select all
print 'The cat is %s the bag' % 'out'
IMO this method is much simpler than 'str.Format', however, I also think that this method isn't as powerful in capabilities in comparison.

Re: Python Basics: String Formatting

Posted: Mon Dec 22, 2014 7:01 pm
by comathi
SumCode wrote:
Also, if I remember correctly, you can format strings using '%s'. So like this
Code: Select all
print 'The cat is %s the bag' % 'out'
IMO this method is much simpler than 'str.Format', however, I also think that this method isn't as powerful in capabilities in comparison.
You're absolutely right. Python can also format strings in a manner similar to Java, but the .format() method is recommended because fields can be reused. Both methods work, though :)