Whether it's a database query or results of mathematical operations, the Python string format method offers a more dynamic and appealing way to present results to a user.
Let's take a look at how the str.format() function works in Python. You'll also find out how you can use this format in your own programs.
How Does the Python String format() Work?
The Python str.format() function lets you insert your results anywhere in a string.
It works by allocating space for your results within the string using curly braces. It then writes your output to that position using the format() method.
The strings outside the brace are what you call literal texts.
How to Use Python String format() Method
The str.format() function accepts a value and an optional string format specifier.
Here's what the general syntax looks like:
str.format(value, format_spec)
Now let's take a look at more practical examples of how to use this Python string method.
1. Insert a Value in a Specific Position
Here's a basic example of how to insert a value into a string using the str.format() method:
Cost = 45
formattedMethod = "This good costs {} dollars only"
print(formattedMethod.format(Cost))
Output: This good costs 45 dollars only
The above code is the same as:
formattedMethod = "This good costs {} dollars only"
print(formattedMethod.format(45))
Output: This good costs 45 dollars only
2. Insert Multiple Outputs Into a String
You can also insert multiple results into a string. Here's how:
y = 7*8
f = 5+5
g = 0
a = "The value of y is {}, while f is {}. Nobody can see {}".format(y, f, g)
print(a)
Output: The value of y is 56, while f is 10. Nobody can see 0
3. Use Escape Braces to Place Outputs in Dedicated Braces
If you need to place any of the results in a curly bracket, that's easy. You only need to introduce two additional escaping braces.
For instance, say you want y in a dedicated curly brace:
a = "The value of y is }, while f is {}. Nobody can see {}".format(y, f, g)
print(a)
Output: The value of y is {56}, while f is 10. Nobody can see 0
4. Output Values From a List
You can select specific values from a list and insert them into a string:
myList = [10, 2, 4, 6]
print(("The first is {} and the third is {}").format(myList[0], myList[2]))
Output: The first is 10 and the third is 4
To avoid repetition within the .format() parenthesis, you can set the format specifier to point to a single variable instead.
Here's how to do that:
myList = [10, 2, 4, 6]
print(("The first is {yourList[0]} and the third is {yourList[2]}").format(yourList = myList))
Output: The first is 10 and the third is 4
The above instance applies to other examples we've treated earlier, too. So, you can play around with them using this trick.
5. Insert Values From a Dictionary
Similarly, as you did in the previous section, you can use the str.format() method to insert a dictionary value into a string:
myDiction = {"Ten":10, "Two":2, "Four":4, "Six":6}
print(("The first is {} and the third is {}").format(myDiction["Ten"], myDiction["Four"]))
Output: The first is 10 and the third is 4
And if you want to use the trick from the previous section:
myDiction = {"Ten":10, "Two":2, "Four":4, "Six":6}
print(("The first is {Ten} and the third is {Four}").format(**myDiction))
Output: The first is 10 and the third is 4
You can also write the above code as:
print(("The first is {d[Ten]} and the third is {d[Four]}").format(d=myDiction))
Output: The first is 10 and the third is 4
6. Insert the Output of a Function Into a String
If you want to show the output of a function in a string:
def difNums(a, b):
if a > b:
return a - b
else:
return return "You can't substract {} from {} using this function".format(a, b)
print(("Hey there: {}").format(difNums(2, 6)))
Output: Hey there: You can't substract 2 from 6 using this function
Using Python String Format Specifiers
The format specifier lets you choose how your format comes through. As mentioned earlier, it's an optional parameter that comes with str.format().
Using this option, you can align your output, cut down long strings, group outputs, or round an integer to a specific number of significant figures, and even more.
You'll often write the format specifiers inside the curly braces. But you can also state them explicitly inside the .format() parenthesis.
Let's go ahead and see some of its use cases.
7. Align String Output
You can use the greater (>) sign to align a string output to the right:
print("Hello {:>15}".format(12734589))
Output: Hello 12734589
You can also align your text to the center if you want:
print("Hello {:^15}".format(12734589))
Output: Hello 12734589
Let's format the above output further. For instance, you can include underscores to see the padding on either side of your string output:
print("Hello {:_^15}".format(12734589))
Output: Hello ___12734589____
But as earlier mentioned, you can state the format specifier explicitly as a parameter within str.format().
So, the previous code looks like this in that case:
print("Hello {:{g}}".format(12734589, g = "_^15"))
Output: Hello ___12734589____
Feel free to rewrite the other examples using the above option.
8. Format Outputs to a Specific Number of Significant Figures
You might also want to return a particular number of significant figures for a calculation using the .format() method.
The example code below, for instance, rounds the result of the mathematical operation to one significant decimal number:
calcprofitPerc = ((45 - 20)/45)*100
formattedOutput = "Our profit on this is {profit: .1f}%"
print(formattedOutput.format(profit = calcprofitPerc))
Output: Our profit on this is 55.6%
9. Truncate Long Strings
Although truncating a text may seem impractical, you can't tell where you might need it.
Here's how to cut off part of your string output using the str.format() function:
print(("Truncate this to the first 3 alphabets: {:.3}").format("idowuomisola"))
Output: Truncate this to the first 3 alphabets: ido
10. Separate Group of Numbers Using a Criteria
You can separate a group of numbers using an underscore or a comma:
print("Separated by underscore: {:{g}}".format(12734589, g="_"))
print("Separated by comma: {:{g}}".format(12734589, g=","))
Output:
Separated by underscore: 12_734_589
Separated by comma: 12,734,589
Moreover, you can specify the group of numbers you want to treat using its key:
print("First numbers by underscore: {0:{g}}".format(12734589, 123674, 662772, g="_"))
print("Third numbers by comma: {2:{g}}".format(12734589, 123674, 662772, g=","))
Output:
First numbers by underscore: 12_734_589
Third numbers by comma: 662,772
Present Outputs Nicely With Python String format() Method
One of the ways you can make your program stand out is how you present results and queries. Undoubtedly, the Python string format method offers a cleaner way to output results. Unlike the previous modulo method of old Python versions, the new string format introduced in Python 3 is more readable and human-friendly.