You are currently viewing Python String Formatting Explained

String formatting in Python allows you to include values from variables within a string, rather than having to concatenate multiple strings together. You can format strings using % operator, format(), f-strings, and String Template Class. In this article, I will explain string formatting by using all these methods with examples.

Advertisements

Methods to format strings in python-

  • The % operator – This allows you to include values from variables in a string by using the % operator followed by a tuple of values.
  • The format() method – This allows you to include values from variables in a string by using curly braces {} as placeholders. The values to be inserted into the placeholders are passed to the format() method as arguments, in the order in which they appear in the string.
  • F-strings (short for “formatted string literals”) provides a concise and convenient way to embed expressions inside string literals, making it easy to include values from variables directly within a string.
  • String Template Class – The string.Template class provides a way to create simple string templates that can be used to substitute values into the string. The placeholders in the template are specified using the $ symbol followed by a valid Python identifier.

1. Format String Using % Operator

The % operator is used to format strings in Python. For example, %s represents a string placeholder, %d represents an integer placeholder, and %f represents a floating-point number. The values to be formatted are passed in a tuple after the % operator.


# Format string using % operator
name = "smith"
year = 1994
print("My name is %s and I born in year %d." % (name, year))

# Output
# My name is messi and I born in year 1994.

In the above example, %s and %d are special characters that indicate that a string and an integer variable should be formatted, respectively. The % operator is used to combining the format string with the variables name and year.

You can use the %d format specifier to convert an int value to a string.


# Use % Operator
num = 6
print('I have %d apples' % num)

# Output
# I have 6 apples

Here are some other common special characters that can be used with the % operator.

Formatting Special CharacterDescription
%sstring
%d or %iinteger
%ffloat
%x or %Xhexadecimal notation
%e or %Eexponential notation
Format String Using % Operator

1.1 Injecting Multiple Strings Using % Operator

You can format multiple strings in a single call using the % operator by passing multiple values in a tuple after the % operator. For example, The order of the values in the tuple must match the order of the placeholders in the string. The values will be formatted and inserted into the string in place of the corresponding placeholders.


# Injecting multiple strings using % operator
name = "messi"
age = 32
city = "california"
print("My name is %s, I am %d years old and I live in %s." % (name, age, city))

# Output:
# My name is messi, I am 32 years old and I live in california.

Follow the below examples, the string 'spoke' is inserted in the place of the %s placeholder, the integer 5 is inserted in the place of the %d placeholder.


# Using % operator
print('Smith stood up and %s to the crowd.' %'spoke')
print('There are %d cats.' %5)

# Output
# Smith stood up and spoke to the crowd.
# There are 5 cats.

1.2 Float Point Precision Using % Operator

You can specify the precision of floating-point numbers in a string using the % operator in python and the dot (.) character. The . character followed by a number specifies the number of decimal places to round the floating-point number. For example, the floating-point number value is rounded to 2 decimal places and inserted into the string in place of the %.2f placeholder.


# Float point precision using % operator
value = 3.14159265
print("The value of Pi is approximately %.2f." % value)

# Output
# The value of Pi is approximately 3.14.

# Using float point
print('The value of pi is: %5.3f' %(3.141592))

# Output
# The value of pi is: 3.142

Following is another example of floating point numbers.


# Using floating point numbers
value = 15.183
print('Floating point numbers: %1.0f' %(value))

# Output
# Floating point numbers: 15

1.3 Use Multiple Format Conversion Types

You can use multiple format conversion types in a single print statement by using multiple instances of the % symbol and specifying different format conversion types for each one. For example,


# Use multiple format conversion types 
# Single print statement
var = 17
str = "Variable as integer = %d \n\
Variable as float = %f" %(var, var) 
print (str)

# Output:
# Variable as integer = 17 
# Variable as float = 17.000000

2. Using format() Method to Format String

Alternatively, you can use the format() method in Python that provides a flexible and powerful way of formatting strings. It allows you to specify placeholders in a string, which can be filled with values from variables or expressions. The syntax is "{}".format(value), where {} a placeholder and value are the data you want to insert into the string.

2.2 Syntax of String format() Method

Following is the syntax of the format() method


# Syntax of format() function
"{}".format(value)

# Syntax of multiple placeholders
"{}{}".format(value1, value2)

2.3 Parameter of format()

  • value: the value is the data you want to insert into the string. Can be an integer, floating point numeric constant, character, or even variable.

# Using string format() function
text = "For only {price:.2f} dollars!"
print(text.format(price = 82))

# Output
# For only 82.00 dollars!

# string format() function
text = "I have {price:.2f} Ruppes!"
print(text.format(price = 32))

# Output
# I have 32.00 Ruppes!

2.4 Use Single Formatter

You will use the string bracket notation program to demonstrate the str.format() method. For example, {} is a placeholder for the value of the name variable, and format() inserts the value of the name into the string. The resulting string is then printed to the console.


# using format option for a
# value stored in a variable
str = "I love {}"
print(str.format("SparkByExample.Com"))

# Output
# I love SparkByExample.Com
 
# formatting a string using a numeric constant
print("Hello, I am {} years old !".format(34))

# Output
# Hello, I am 34 years old!

2.5 Use Multiple Placeholders

You can also use multiple placeholders in Python format() method. For example, the below snippet uses two placeholders {} with the values from variables first_name and last_name.


# Multiple placeholders
first_name = "SparkbyExamples"
last_name = "Com"
print("Hello, {} {}!".format(first_name, last_name))

# Output
# Hello, SparkbyExamples Com!

# Use string format() with multiple placeholders
print("I love {} {} {} {}"
      .format("Spark", "By", "Examples", "com"))
      
# Output
# I love Spark By Examples com

2.6 Use string format() IndexError

The IndexError in the format() method of Python occurs when the number of placeholders in the format string does not match the number of values being passed to the format() method. For example, there is only one placeholder {} in the format string, but two values are being passed to the format() method.


# Use string format() IndexError
name = "SparkbyExamples"
print("Hello, {} {}!".format(name))

# Output
# IndexError: Replacement index 1 out of range for positional args tuple

2.7 Formatting Types

  • 'd': This format code is used to format an integer value as a decimal number.
  • 'f': This format code is used to format a floating-point number as a decimal number with a specified number of decimal places.
  • 'b': This format code is used to format an integer value as a binary number.
  • 'o': This format code is used to format an integer value as an octal number.
  • 'x': This format code is used to format an integer value as a hexadecimal number.
  • 's': This format code is used to format a string value as a string.
  • 'e': This format code is used to format a floating-point number in exponential notation, with a specified number of decimal places.

3. Formatted String Using F-strings

F-strings (Formatted String Literals) is a new way to format strings in Python 3.6 and later versions. It uses an “f before-the-opening quote to indicate that this is a formatted string. Variables are enclosed within {} inside the string and their values are evaluated during runtime. The expression inside {} is evaluated and its value is concatenated into the string.


# Using F-strings
name = "Smith"
age = 33
print(f"My name is {name} and I am {age} years old.")

# Output
# "My name is Smith and I am 33 years old."

3.1 Arithmetic Operations Using F-strings

You can perform arithmetic operations within an f-string by placing the calculation within the curly braces, For example,


# Arithmetic operations using F-strings
x = 10 
y = 15
print(f"He said his age is {2 * (x + y)}.")

# Output
# He said his age is 50.

3.2 Lambda Expressions Using F-strings

You can use lambda expressions within an f-string in the same way as you would use any other expression. The value returned by the lambda function is then concatenated into the string.


# Lambda expressions using F-strings
add = lambda x, y: x + y
print(f"The sum of 5 and 3 is {add(5, 3)}")

# Output: The sum of 5 and 3 is 8

# Lambda expressions 
print(f"He said his age is {(lambda x: x*5)(7)}")

# Output
# He said his age is 35

3.3 Float Precision Using F-strings

You can also use the Float precision using F-strings, For example, 2f specifies a precision of 2 digits after the decimal point. You can change the number to control the precision.


# Float precision using F-strings
num = 10.123456
print(f"The value of pi is: {num:.2f}")

# Output
# The value of pi is: 10.12

# Float precision
num = 4.61728
print(f"The value of pi is: {num:{1}.{5}}")

# Output
# The value of pi is: 4.6173

4. Use String Template Class

Similarly, you can use the string Template class as a convenient way to substitute placeholders in strings with user-specified values in Python. It provides a simple way to perform string substitutions without having to use string concatenation or the format() method. The placeholders in the string are identified by a specific syntax, usually, dollar signs $ followed by a placeholder name.


from string import Template
# Use string template class
template = Template("My name is $name and I am $age years old.")
substituted = template.substitute(name="Smith", age=23)
print(substituted)

# Output
# My name is Smith and I am 23 years old.


from string import Template
# Use string template class
n1 = 'Hello'
n2 = 'SparkByExamples.com'
template = Template('$n3 ! This is $n4.')
print(template.substitute(n3=n1, n4=n2))

# Output
# Hello ! This is SparkByExamples.com.

Conclusion

In this article, I have explained how to format Strings in Python by using % operator, format(), f-strings, and string Template class with examples.

Happy Learning !!