SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software
Python Programming and Python Code Tutorials for Programmers

String Format Function with Multiple Variables Python Code Sample

In Python programmers can easily replace variables in a given string value using string format function. I want to show different ways of displaying multiple variables within a string using format function in Python 3 and in Python 2. This Python tutorial includes sample Python code blocks demonstrating use of string format function.

Display String by Replacing Variables using Python Format String Function

With Python 3, everything can be assumed as objects like strings. Using the format() method of string object, variables with placedholders within the string expression can be evaluated easily.

Here is two ways of displaying string objects with multipe variables using Format function.

In below example, I created a Python function named "compare" which accepts two input variables and compares them arithmetically displaying the comparison result as a single line of string expression.

def compare(x,y):
   if x < y:
      print('x value {} is smaller than y value {}'.format(x,y))
   elif x == y:
      print('x value {} is equal to y value {}'.format(x,y))
      print('x value {} is greater than y value {}'.format(x,y))

x = 26; y = 64; compare(x,y)
x = 1068; y = 462; compare(x,y)
x = 6; y = 6; compare(x,y)
String Format Function Python Code Sample

Following screenshot shows the execution output of the above Python code block on Visual Studio

multiple variables with Python string format function

Here is another way of formatting a string value with multiple variable values.
This time the variables are directly referenced within the curly braces {}
This time format function is at the beginning of the string expression

movie = "Parasite"
country = "South Korea"
boxoffice = 258822018

movie_info = f'The movie "{movie}" from {country} made worldwide box office around ${boxoffice}'
String Formatting with Multiple Variables in Python

And the output of the above Python code script is seen below

formatting string with variables in Python

Since there are changes in behaviour of string object between Python version 3 and Python version 2, below code sample code can also help you to format string expressions with variables.

myString = 'My name %s and I am %d years old.'
print(myString % ('Kodyaz.com', 17))
Formatting string in Python programming

Here is the displayed output after the execution of the sample Python code

string formatting in Python programming

I hope Python developers will find useful these hints and sample Python script codes for formatting string expressions including multiple variables.

Python Tutorials

Copyright © 2004 - 2021 Eralper YILMAZ. All rights reserved.