
Please support if you like my work by payment through upi: sinhamit@icici or payment by bank
account name: Amit Kumar Sinha,
account number: 2646728782
IFSC code: KKBK0005660
SWIFT: KKBKINBB
Inserting Variables into Strings in Category: Python by amit
🕙 Posted on 2023-07-28 at 19:39:54 Read in Hindi ...
Formatting Styles: Other Ways to Concatenate Strings
%, format(), f-string
The % operator is the oldest among these three way of formatting and inserting variables into strings. f"{variableName} OtherTexts"
(known as f-string) is introduced in Python 3.6, and it is more readable and easier to implement/%
placeholder and format()
string method (which was introduced in Python 2.6). In the matter of speed / performance, the % placeholder is the fastest, and the .format() string method is slower than other two formatting styles.
% operator/ placeholder
In the following example, three variables namely, my_str (string data-type), my_int (integer data-type), and my_float (float data-type), are used to be placed inside the parent string, at desired positions. The % operator requires exactly as many items/()
parentheses. The %
placeholder to be inserted, is of three kinds:
(1) %d is to insert/
(2) %f is to insert/
(3) %s is to insert string and all other data-types.
The % placeholder cannot insert objects and attributes into the parent string. You can see in the following example, that when the variable my_float (float data-type) is intentionally inserted to the %d (integer) placeholder, the output is truncated to integer value. You can also see that blank (white-) spaces left inside a pair of single/
You should note that you cannot pass string values for %d (integer) or %f (float) placeholders. Also, you cannot place list (that is, square brackets) after the % operator. In both these cases, the Python interpreter will output TypeError, as shown below.
my_str = "hello"
my_int = 32
my_float = 32.3
print( " %s %d %f " %
(my_str, my_int, my_float) ) # Outputs hello 32 32.300000
print( " %s %f %d " %
(my_str, my_int, my_float) ) # Outputs hello 32.000000 32
print( " %s %s %s " %
(my_str, my_int, my_float) ) # Outputs hello 32 32.3
print( " %d %s %s " %
(my_str, my_int, my_float) ) # Outputs TypeError as shown below. String data-type is provided at %d (real number) placeholder.
File "C:\xampp\
print( " %d %s %s " % (my_str, my_int, my_float) )
~~~~~~~~~~~^
TypeError: %d format: a real number is required, not str
print( "%s %s %s" %
[my_str, my_int, my_float] ) # Outputs TypeError as shown below, but when you replace square brackets with parentheses, NO ERROR will be displayed.
File "C:\xampp\
print( " %s %s %s " % [my_str, my_int, my_float] )
~~~~~~~~~~~^
TypeError: not enough arguments for format string
%s (string) placeholder
The %s (string) placeholder can hold string, integer, float, boolean data-types, and there must be exact placeholders as many as items/%
placeholder is old way to style formatting since 1990s, when programmers struggles to display FANCY OUTPUT in black screen COMMAND LINE CONSOLE. Thus, there are options to leave spaces, and style text formatting:
print( " %s %s %s " %
( (True, None, 3) ) ) # Outputs True None 3 (None is null
in other programming languages - special data-type)
print( help( None ) ) # Outputs as follows:
class NoneType(object)
| Methods defined here:
|
| __bool__(self, /)
| True if self else False
|
| __repr__(self, /)
| Return repr(self).
|
| -----------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
None
A docstring is used to display variables inside it. The vars()
(without any argument), or locals()
in-built Python function can be used to insert variables (greeting, x, y, a, b, c) inside string literals, as shown in below example:
greeting = "Hello World"
x = 10
y = 20
print ( """Greeting = %(greeting)s
x, y = ( %(x)s, %(y)s )""" % vars()
)
print ( "Greeting = %(greeting)s x, y = ( %(x)s, %(y)s )" % locals()
)
# You can directly pass values in a dictionary literal, to variables:
print( '%(a)s %(c)s %(b)s' % {'a': 10, 'b': 50, 'c': 30} )
x, y = ( 10, 20 )
Greeting = Hello World x, y = ( 10, 20 )
10 30 50
vars()
is a Python built-in function, which behaves like locals()
when no argument is passed inside parentheses. vars() returns a dictionary of:
(i) the current namespace (if called with no argument), or
(ii) the argument passed within the parentheses.
print( help( vars ) ) # Outputs as follows
vars(...)
vars([object]) -> dictionary
Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
None
print( help( locals ) ) # Outputs as follows
locals()
Return a dictionary containing the current scope's local variables.
NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.
None
%d and %f placeholders
These two placeholders are mainly used to insert integers and floats specifically. These two can be formatted as required by the programmers in their codes. In the following example, the floating point number assigned to variable my_num (approximate value of PI) is truncated to fifth place after decimal point. These floating point numbers are irrational numbers (infinite decimal values, for example, 22/7). Complex numbers are different from irrational numbers. Rational numbers are fixed fractional (floating point) values (that is, finite digits after decimal point).
my_num = 3.14159265
print("%.5f
" % my_num) # Outputs 3.14159 (dot . symbol is important after % placeholder)
%d, %o (not zero, but letter 'o'), %e are placeholders to insert numbers (from 0 to 9), octal (from 0 to 7) and floating point (in exponential) values are displayed respectively.
print( " %d " % 456 ) # Outputs 456
print( " %o " % 456 ) # Outputs 710 (It is not numeric decimal, but ocatal representation of 456.)
print( " %e " % 456 ) # Outputs 4.560000e+02 (e+2 means 102 that is 10×10)
format() method
You can get help documentation, by executing print( help( str.format ) ) statement. The format()
method uses curly braces as placeholder inside the parent string, and variables are provided within ()
parentheses just after the .format. These variable names are indexed starting from 0 (zero), and when these index numbers are not provided within curly braces, variables are placed in respective order.
print( "1. name is {}.".format
( 'Amit' ) )
print( '2. name is {} and age is {}.'.format
( 'Amit', '42' ) )
print( "3. name is {1} and age is {0}.".format
( 'Amit', 42 ) )
print( "4. name is {x} and age is {y}.".format
( x='Amit', y='42' ) )
print( "5. name is {y} and age is {x}.".format
( x='Amit', y='42' ) )
print( "6. name is {y} and age is {y}.".format
( x='Amit', y='42' ) )
2. name is Amit and age is 42.
3. name is 42 and age is Amit.
4. name is Amit and age is 42.
5. name is 42 and age is Amit.
6. name is 42 and age is 42.
In the output of above example, you can see that in line 3, where 1 (one) is provided in first pair of curly braces, and 0 (zero) is provided in second pair of curly braces, the result is not same as shown in line 2. Similarly, variable names, x and y are reversed in lines 4 and 5. The output in these line numbers 4 and 5 is also reversed. In line 6, only variable y is provided in both pair of curly braces, and therefore, only value assigned to it is displayed in OUTPUT.
There are many advanced features provided in format()
method, which will be explained to you later. To escape the % character within the pair of single/
num = int( input( "Enter an integer value: " ) )
binary_num = "{0:b}
".format(num)
print( "Binary representation of ", num, " is ", binary_num)
num = int( input( "Enter an integer value: " ) )
octal_num = "{0:o}
".format(num) # before colon, digit is zero; and after colon, it is letter 'o'
print( "Octal representation of ", num, " is ", octal_num)
f -string
f-string is the latest formatting style, in which you can use expressions within the curly braces (that is, you can apply appropriate built-in functions or methods on the variable names or literals). Unlike other programming languages (such as PHP and JavaScript), you can use either a pair of single quotes or a pair of double quotes, in all three way of formatting in Python.
name = "Amit"
age = 42
# Formatting with the % operator
print( 'Dear %s, you are %d years old.' %
(name, age) )
print( "Dear %s, you are %d years old." %
(name, age) )
# Formatting with the format() method
print( 'Dear {}, you are {} years old.'.format(name, age) )
print( "Dear {}, you are {} years old.".format(name, age) )
# Formatting with the f string
print( f
'Dear {name}, you are {age} years old.' )
print( f
"Dear {name}, you are {age} years old." )
print( f
"Dear {name.upper()}, you are {abs( age )} years old." )
There are other string methods, such as expandtabs()
, center()
, ljust()
, rjust()
, etc. to make spaces (tab), align texts in center, left or right, accordingly. However, these methods are generally used in (black screen) Command Prompt/format_map()
method is similar to format()
, but it uses mapping as argument. There are more way of formatting and concatenating strings and inserting variables into them. You will learn about string
module, StringIO class from io
module, etc. in later chapters.
Leave a Comment:

Amit Sinha March 2nd, 2023 at 9:30 PM
😃 😄 😁 😆 😅 😂 😉 😊 😇 😍 😘 😚 😋 😜 😝 😶 😏 😒 😌 😔 😪 😷 😵 😎 😲 😳 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 😤

Ribhu March 3rd, 2023 at 9:30 PM
🐵 🐒 🐶 🐩 🐺 🐱 🐯 🐅 🐆 🐴 🐎 🐮 🐂 🐃 🐄 🐷 🐖 🐗 🐽 🐏 🐑 🐐 🐪 🐫 🐘 🐭 🐁 🐀 🐹 🐰 🐇