Home Python How to format strings in Python

How to format strings in Python

Python string formatting is a valuable tool for Python programmers daily. Strings appear to be formatted similarly in each coding language. It’s also a big reason we utilize scripting languages in the first place.

The f string method and .format() and concatenation are the most popular approaches to formatting strings. With most legacy libraries supporting Python3, we may see the Python2 syntax fade away.

We’ll look at how to format strings in Python in this tutorial. Dynamically infusing things into a string and presenting it is known as string formatting. You can do string formatting in five different ways:

  • Using the percent operator to format.
  • The .format() string method is used to format the data.
  • f-strings are string literals that are used to format data.
  • String Template Class Formatting
  • Using Concatenation

So we’ll look at all of the methods described above. And identify which string formatting style is the best.

String format() method in Python

The .format() function was introduced in Python 3 to make it easier to handle sophisticated string formatting. Formatters work by inserting replacement fields and placeholders into a string and using the str.format() function. The value we want to put in the placeholders concatenated with the text supplied to the format method as parameters.

Syntax:

 'The starting point is here {} then also {}'.format('code1′,'code2')

Example: Formatting any string using the format() method

print('We all are {}.'.format('equal'))

Compared to the placeholder approach, the .format() method provides a lot of advantages:

  1. We can use an index-based location to insert an object:
print('{2} {1} {0}'.format('is home to programming','Underscored', 'Code'))
  1. Using specified keywords, we can subsequently insert objects:
print('a: {x}, b: {y}, c: {z}'.format(x = 122,y = 'Two', z = 89.23))
  1. To avoid repetition, we can reuse the added objects:
print('The first {c} was alright, but the {c} {c} was tough.'.format(c = 'code'))

With the .format() method, you can get float precision:

Syntax: {[index]:[width][.precision][type]}

The type is highly ideal to use with format codes:

  • ‘d’ for integers
  • ‘f’ for floating-point numbers
  • ‘b’ for binary numbers
  • ‘o’ for octal numbers
  • ‘x’ for octal hexadecimal numbers
  • ‘s’ for string ‘e’ for floating-point in an exponent format

Example

Inside the placeholder, type the price in fixed point, two-decimal format:

txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))

The format() method formats and inserts the provided value(s) into the string’s placeholder. On the other hand, curly brackets are responsible for defining the placeholder. In the Placeholder section below, you may learn more about the placeholders.

The format() method return value is a formatted string.

The syntax is as follows:

string.format(value1, value2…)
Parameter ValuesParameter Description
value 1, value 2…Required. There should be one or more values prepared and put into the string. The values can be a comma-separated list of values, a key=value list, or a combination of both. You can use any data type for the values.

The placeholders

Named indices like price, numbered indexes like {0} and you can even use empty placeholders can be used to identify placeholders {}.

Changing the placeholder values:

# named indexes:
string_one = "The language name is {languagename}, and the age is {Lage}".format(languagename = "Java", age = 50)
# numbered indexes:
string_two = "The language name is {0}, and the age is {1}".format("Java",50)
# empty placeholders:
string_three = "The language name is {}, and the age is {}".format("Java",50)

print(string_one)
print(string_two)
print(string_three)

Types of Formatting

You can add a formatting type to the placeholders for result formatting:

:< Left is responsible for aligning the result within the available space

# To demonstrate, we insert the number 8 to set the available space for the value to 8 characters.
# Use "<" to left-align the value:
txt_val = "We have {:<8} machines."
print(txt_val.format(83))

:> The right has to align the result within the available space

# To demonstrate, we insert the number 8 to set the available space for the value to 8 characters.
# Use ">" to right-align the value:
txt_val = "We have {:>8} machines."
print(txt_val.format(83))

:^ Center’s mandate is to align the result within the available space

# To demonstrate, we insert the number 8 to set the available space for the value to 8 characters.
# Use "^" to center-align the value:
txt_val = "We have {:^8} machines."
print(txt_val.format(83))

:= Places the sign to the leftmost position

# To demonstrate, we insert the number 8 to specify the available space for the value.
# Use "=" to place the plus/minus sign at the leftmost position:

txt_val = "The temperature is {:=8} degrees celsius."
print(txt_val.format(-5))

:+ Using the plus sign indicates whether the outcome is positive or negative

:- Use of a minus is solely for negative values

# Use "-" to always indicate if the number is negative (positive numbers are displayed without any sign):

txt_val = "The temperature is between {:-} and {:-} degrees celsius."
print(txt_val.format(-3, 7))

: Use space to insert an extra space before positive numbers (and a minus sign before negative numbers)

:, Use a comma as a thousand separator

# Use "," to add a comma as a thousands separator:

txt_val = "The universe is {:,} years old."
print(txt_val.format(13800000000))

:_ Use an underscore as a thousand separator

# Use "_" to add an underscore character as a thousands separator:
txt_val = "The universe is {:_} years old."
print(txt.format(13800000000))

:b Binary format

# Use of "b" is ideal for conversion of the given number into an equivalent binary format:
txt_val = "The resultant binary version of {0} is {0:b}"
print(txt_val.format(5))

:c Is responsible for converting the said value into the corresponding Unicode character

:d Decimal format

# Use "d" to convert a number, in this case, a binary number, into decimal number format:
txt_val = "We have {:d} machines."
print(txt_val.format(0b101))

:e Scientific format, with a lower case e

# Use of "e" is ideal in converting a number into scientific number format (with a lower-case e):
txt_val = "We have {:e} machines."
print(txt_val.format(5))

:E Scientific format, with an upper case E

# The use of "E" is for number conversion into a scientific number format (with an upper-case E):
txt_val = "We have {:E} machines."
print(txt_val.format(5))

:f Fixpoint number format

# Use the "f" for converting a number into a fixed point number, default with six decimals, but use a period followed by a number to specify the number of decimals:

txt_val = "The price is {:.2f} dollars."
print(txt_val.format(45))

# without the ".2" inside the placeholder, it will display this number like this:
txt_val = "The price is {:f} dollars."
print(txt_val.format(45))

:F Fixpoint number format, in uppercase format (show inf and nan as INF and NAN)

# Use the "F" for converting a number into a fixed point number while displaying inf and nan as INF and NAN:
x = float('inf')
txt_val = "The price is {:F} dollars."
print(txt_val.format(x))

# same example, but with a lower case f:
txt_val = "The price is {:f} dollars."
print(txt_val.format(x))

:g General format

:G General format (using an upper case E for scientific notations)

:o Octal format

# Use the "o" in converting the number into octal format:

txt_val = "The octal version of {0} is {0:o}"
print(txt_val.format(10))

:x Hex format, lower case

# Use "x" to convert the number into Hex format:

txt_val = "The Hexadecimal version of {0} is {0:x}"
print(txt_va.format(255))

:X Hex format, upper case

# Use of the "X" for converting the specified number into an equivalent upper-case Hex format:

txt_val = "The Hexadecimal's version of {0} is {0:X}"
print(txt_val.format(255))

:n Number format

:% Percentage format

# The use of "%" for converting the number into a percentage format:

txt_val = "Your score is {:%}"
print(txt_val.format(0.25))

# Or, without any decimals:

txt_val = "You scored {:.0%}"
print(txt_val.format(0.25))

Example:

print('pi’s valueof is: %1.5f' %3.141592)

vs.

print('pi’s valueof is: {0:1.5f}'.format(3.141592))

Using the percent(%) operator to format a string

It’s the most traditional way to format strings. The modulo percent operator is used here. The “string-formatting operator” is another name for the modulo percent. In fact, the percent operator can access a unique built-in operation in Python strings. It makes it very simple to do simple positional formatting. If you’ve ever used a printf-style function in C, you’ll immediately realize how this works.

Example: Using the percent operator to format a string

print("The mangy, scrawny stray dog %s gobbled down the grain-free, organic dog food." %'hurriedly')

You can also inject many texts simultaneously and put objects in the string using variables.

Example: Injecting multiple strings using the % operator

x_val = 'looked'
print("Code %s and %s around"%('walked',x_val))

‘%s’ is used to inject strings in the same way that ‘% d’ is used to inject integer numbers, ‘% f’ is used to inject floating-point values, and ‘% b’ is used to inject binary format.

print('Joe stood up and %s to the crowd.' %'spoke')
print('There are %d dogs.' %4)

Precision floats using the placeholder method:

The format for floating-point numbers is %a.bf. If the complete number does not include this many digits, a would-be the minimal number of digits in the string; these could be padded with white space. Closely related, bf denotes the number of digits following the decimal point.

Consider the following examples:

Example 1: Float point precision using the % operator

print('The value of pi is: %5.4f' %(3.141592))
print('Floating point numbers: %1.0f' %(13.144))

Example 2: You can use multiple format conversion types in a single print statement

variable = 12

string_val = "Variable as integer = %d \n\ Variable as float = %f" %(variable, variable)
print (string_val)

Example:

'Hello, %s' % name

We’re telling Python were to substitute the value of name, represented as a string, with the %s format specifier.

Other format specifiers are available for controlling the output format. For example, to create adequately written tables and reports, you can convert integers to hexadecimal notation or include whitespace padding. To convert an int value to a string and represent it as a hexadecimal number, use the % x format specifier:

'%x' % errno

If you want to make numerous substitutions in a single string, the “old style” string formatting syntax changes slightly. Because the percent operator only accepts one parameter, the right-hand side must be wrapped in a tuple, as shown below:

errno = 50159747054
username = 'code'

'Hey %s, there is a 0x%x error!' % (username, errno)

If you supply a mapping to the percent operator, you can additionally refer to variable substitutions by username in your format string:

errno = 50159747054
username = 'code'

'Hey %(username)s, there is a 0x%(errno)x error!' % { "username": username, "errno": errno }

It makes it easy to maintain and adjust your format strings in the future. You don’t have to worry about the order in which the values are passed. That is as far as matching the order in which they are referenced in the format string. The disadvantage is that this method necessitates a little more typing.

I’m sure you’ve wondered why this printf-type string formatting is referred to as “old style.” It was technically supplanted by Python 3’s “new style” formatting, which we’ll discuss next.

Using F-strings to format a string

Literal String Interpolation, or F-strings, is a new string formatting mechanism proposed by PEP 498. The reason for this is the leading f character preceding the string literal. F-strings are designed to make string interpolation easier.

Prefix the string with the letter ” f ” to make an f-string. You can format the string itself in the same way that you would with str.format (). F-strings are a quick and easy technique to format strings by embedding python expressions inside the string literal.

Example: String Formatting with F-Strings

name = 'Ele'
print(f"My name is {name}.")

This new formatting syntax is exceptionally versatile and straightforward to use. You may also use it to insert arbitrary Python expressions and perform arithmetic calculations.

Example: Arithmetic operations using F-strings

a = 5

b = 10

print(f"He said his age is {2 * (a + b)}.")

You can also use Lambda expressions in f-string formatting.

Example: Lambda Expressions using F-strings

print(f"He said his age is {(lambda x: x*2)(3)}")

The precision of floats in the f-String method:

Syntax: {value:{width}.{precision}}

Example: Float Precision using F-strings

num = 3.14159
print(f"The valueof pi is: {num:{1}.{5}}")

String Template Class

Template Class in the String module allows us to construct reduced output specification syntax. $ forms placeholder names with valid Python identifiers in this format (alphanumeric characters and underscores). Enclosing the placeholder in braces can be followed by more alphanumeric letters without any gaps. When you type $$, you get a single escaped $:

Example: Formatting string using Template Class

# Python program to demonstrate
# string interpolation
from string import Template

n1 = 'Hello'
n2 = 'Codeunderscored'

# made a template which we used to pass two variable so n3 and n4 formal and n1 and n2 actual
n = Template('$n3 ! This is $n4.')
# and pass the parameters into the template string.
print(n.substitute(n3=n1, n4=n2))

Using Concatenation to Format a String

print(‘Hello’+name)

It is the most basic – and consequently the most straightforward – approach to learning. It’s also how we prefer to instruct someone new to coding. It’s simple to understand without a prior understanding of coding because the pieces are in literal sequence, and the ‘+’ operators are used.

company_name = 'Codeunderscored'
c_year = 2022

string = 'Hello, ' + company_name
print(string)

string = company_name + ' was started in ' + str(c_year)
print(string)

The examples shown above construct a formatted string by joining variables with the addition operator. It’s important to remember that we’ll need to convert all variables to strings. The variable company_name is already a string, and the c_year is an integer.

Which type of string formatting is the most effective?

Both percent -formatting and str.format() are slower and less effective than f-strings (). Expressions in f-strings are evaluated at runtime, and we can embed expressions within f-strings using a fundamental and straightforward syntax.

The phrases inside the braces are evaluated at runtime, then combined with the f-string string’s component, and returned to the final string.

Is it essential to learn and use all of these string formatting methods?

When learning Python, you’ll need to know all of this. Even if you don’t use the old string formatting often, it’s still used in some more senior forums, Stack Overflow articles, and many older Machine Learning frameworks. As a result, knowing them will help you recognize what’s going on and maybe debug an issue.

You can use any of the other three methods we described here to format your strings in Python. Choose the one that best fits the situation and even your mood on that day!

When working with short and simple sentences, the + comes in handy. It’s also helpful in creating debugging states when working on a modest project. For example, we could utilize the + operator to create a basic number guessing game.

The .format() or f string methods may be preferable when adding logging statements because they make your statements more modular. It will also be simpler to describe the data type’s precision and formatting.

Conclusion

Surprisingly, there are multiple approaches to string formatting in Python. Each strategy has its own set of advantages and disadvantages. Which method you should choose will be determined by your use case.

When you’re coding in Python, you’ll have to format strings all the time. We must eventually print or display every variable, tuple, dictionary, and logic that we define. And each of these, without exception, requires us to convert the required output into a string before printing it or using the appropriate Python function to show it.

Using the traditional % strategy was more common in Python2 when it was still a young and emerging language. For experienced coders with a C programming background, it’s a simple approach to grasp. On the other hand, .format() is used by many Python programmers because this makes things easier for you. F strings are the newest technique that Python3 supports, and they’re quickly gaining popularity.

Template strings is a technique available as a class in the Python standard library’s string module. It’s imported as a module, replacing placeholders with the .substitute() method.

You may also like

Leave a Comment