Python String Format

By | September 27, 2021
Python String Format

Python String Format is a technique, which allows us to insert variable values inside a string using placeholders. To perform string formatting in Python we have 4 four different techniques. Here in this tutorial, we will walk you through all the four different Python String Format techniques and methods.

Python String Format

1. Python old String Formatting with % Operator:

Python string supports a unique operation that can be performed using % operator. If you have ever used C programming language printf() statement, there you have probably used % operator with data specifier to place variable value in a String. Similarly, Python also supports string formatting with % operator.

Vamware

Example

>>> first_name = "Rahul"
>>> last_name = "Singh"
>>> des = "The FirstName is: %s and the last name is %s" %(first_name, last_name)
>>> des
'The FirstName is: Rahul and the last name is Singh'

In the above example, both the %s statements of the des replaced by first_name and last_name. This is because both %s were placeholders for first_name and last_name variables.

The s in the above example is the string Data Type specifier and % is the string formatting operator. There are many other specifiers in Python if you want to put different formatting to the output.

Specifier Description Example
i Integer
>>> "Integer value %i" % 365.376 'Integer value 365'
o Octal format
>>> "Octal value of 354: %o" % 354
'Octal value of 354: 542'
u Obsolete type (similar to i)
>>> "Obsolete %u" % 234.3
'Obsolete 234'
x Signed Hexadecimal format (lower case)
>>> "hexadecimal %x" %349
‘hexadecimal 15d'
X Signed Hexadecimal format (Upper case)
>>> "hexadecimal %X" %-349
'hexadecimal -15D'
e Exponential Formatting. (lowercase e)
>>> "Exponential %e" %343
'Exponential 3.430000e+02'
E Exponential notation (uppercase E)
>>> "Exponential %E" %343
'Exponential 3.430000E+02'
f Displays fixed decimal points number (Up to 6 decimal point)
>>> "Floating %f" %343.37463463746
'Floating 343.374635'
F Similar to ‘f’.
>>> "Floating %F" %343.37463463746
'Floating 343.374635'
g Display floating-point number. Use lowercase exponential of the exponent is greater than 6 digits else use decimal format.
>>> "Floating %g" %3433234
'Floating 3.43323e+06'
G Same as ‘g’. Except it uses to ‘E’ if the number is large.
>>> "Floating %G" %3433234
'Floating 3.43323E+06'
c Represent Single byte object only accept integers.
>>> "single byte %c" %345
'single byte ř'

 

s String specifier
>>> "String %s" %"name"
'String name'

The old Python String Formatting also support variable name substitute

>>> "First name %(fname)s  Last Name %(lname)s" %{'fname':"Rahul", 'lname':"Singh"}
'First name Rahul  Last Name Singh'

This syntax string formatting easier, and you can place access the placeholder with variable names, so you do not have to define the value in the same order as they mentioned in the string.

2. Python String Format() Function (str.format)

Python string has many built-in methods and format() is one of those. Using the Python string format() method we can format a string value and place values in the string placeholders.

The syntax of Python string format() method is similar to Python % string format operator, but here we do not have to use the % symbol.

Python string format() example

>>> fname = "Rahul"
>>> lname= "Singh"
>>> age = 23
>>> print("First Name:{0} Last Name: {1} age: {2}".format(fname, lname, age))
First Name:Rahul Last Name: Singh age: 23

The Python String format() function accepts all the values as parameters and places them in the string according to the index value, as they are specified.

Inside the string, we need to specify the value index number using the curly {} braces so the correct value can be placed in the specified placeholders.

The string format method also support variable substitution, where instead of using index values you can use name as a placeholder to format string.

>>> fname = "Rahul"
>>> lname= "Singh"
>>> age = 23
>>> print("First Name:{fname} Last Name: {lname} age: {age}".format(fname=fname, lname=lname, age=age))
First Name:Rahul Last Name: Singh age: 23

3. Python String Interpolation f-String (Python 3.6+)

Python version 3.6 and above support string Interpolation, which is the easiest way of String Formatting technique. The Python string Interpolation is also known as f-string. In this String formatting technique, we can embed Python expression or variable inside the string object.

Python String Interpolation f-string Example

>>> fname = "Rahul"
>>> lname= "Singh"
>>> age = 23
>>> print(f"First Name:{fname} Last Name: {lname} age: {age}")
First Name:Rahul Last Name: Singh age: 23

For the string interpolation, you need to specify the letter f prefix with the string then using the curly braces you embed Python expression and values in the string constant.

>>> num1= 20
>>> num2 =30

>>> print( f"Sum of {num1} and {num2} is {num1+num2}" )
Sum of 20 and 30 is 50

The place holder of Python f-string can also execute the Python expression.

4. Python String Template Standard Library

Python Standard string module support Template class which can be used for Python string formatting. The template method is less powerful and not used often, but it’s good to know all the possible ways of format a string in Python.

Python string formatting Template Example

>>> from string import Template
>>> string = Template("Hi!, $name $lastname")
>>> string.substitute(name ="Rahul", lastname ="singh")

'Hi!, Rahul singh'

In the above example, you can see that to use the string formatting you need to import the Template class from the string library.

The template string formatting is recommended to format the user entered string.

Conclusion

In your Python programming, you generally use the string.format() method and f-string or string interpolation to the format string. A Pythonista usually does not use the % operator and string Template class to format a string in Python.

You can use any of the above string formatting techniques they all will work fine. If you are formatting a string that is entered by the user then you should consider Python string Template else you can either use string.format() method or f-string, they both are similar.

People are also reading: 

Leave a Reply

Your email address will not be published. Required fields are marked *