Python Basics: String Formatting
3 posts
Page 1 of 1
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:
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:
As I said earlier, the beauty of fields is that they can be reused, let's look at an example of that:
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:

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:
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:
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;
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
This will output "Codenstuff is a great programming forum, it currently has 4952 members""{0} is a great programming forum, it currently has {1} members".format("Codenstuff", 4952)
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
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."{sitename} is a great programming forum, it currently has {members} members".format(sitename="Codenstuff", members=4952)
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
You can probably guess the output of the above code ;)"Do you know {person}, {person}, {person}. Do you know {person} who lives {place}".format(person="the Muffin Man", place="on Drury Lane")
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
In the above code, a list was passed to the format() method, but because its elements can be individually accessed, the code remains valid languages = ["VB.NET", "Java", "Python", "C++"]
"{0[0]}, {0[1]}, {0[2]} and {0[3]} are all programming languages".format(languages)

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
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
Will output 'This account contains 56452.45$'"This account contains {0:10.2f}$".format(56452.45421)
Code: Select all
Will output 'You have ticket number 00020'"You have ticket number {0:05d}".format(20)
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;
Also, if I remember correctly, you can format strings using '%s'. So like this
Code: Select all
IMO this method is much simpler than 'str.Format', however, I also think that this method isn't as powerful in capabilities in comparison.print 'The cat is %s the bag' % 'out'
SumCode wrote:Also, if I remember correctly, you can format strings using '%s'. So like thisYou'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, thoughCode: Select allIMO this method is much simpler than 'str.Format', however, I also think that this method isn't as powerful in capabilities in comparison.print 'The cat is %s the bag' % 'out'

3 posts
Page 1 of 1
Copyright Information
Copyright © Codenstuff.com 2020 - 2023