New style string formatting in Python

In this section, you will learn the usage of the new style formatting.

Learn more here.

Python 3 introduced a new way to do string formatting that was also later back-ported to Python 2.7. 
This “new style” string formatting gets rid of the modulo-operator special syntax and makes the syntax for string formatting more regular.
Formatting is now handled by calling .format() on a string object.
You can use format() to do simple positional formatting, just like you could with “old style” formatting:


name = "Emmanuel"
print("Hello, {}".format(name))


We can also use .format() to do simple positional formatting just like we could with old-style formatting


name = "Emma"
age = 24
print("Hey {}, You are {}!".format(age, name))


Or, you can refer to your variable substitutions by name and use them in any order you want. 
This is quite a powerful feature as it allows for re-arranging the order of display without changing the arguments passed to format()


name = "Emma"
error = 0xbadc0ffee
print('Hey {name}, there is a 0x{error:x} error!'.format(name=name, error=error))


This example shows that the syntax to format an int variable as a hexadecimal string has changed. 
Now you need to pass a format spec by adding a :x suffix.
In Python 3, this “new style” string formatting is preferred over old-style formatting. 
While “old style” formatting has been de-emphasized, it has not been deprecated. It is still supported in the latest versions of Python.
In the next section, I will show you the string literals way of formatting strings that lets you use embedded Python expressions inside string constants.






No comments:

Post a Comment

Note: only a member of this blog may post a comment.

New Post

New style string formatting in Python

In this section, you will learn the usage of the new style formatting. Learn more here . Python 3 introduced a new way to do string formatti...