Thursday 17 December 2020

Python: Insert variable value in a string

Follow below steps to replace a variable value in a string.

a.   Prefix the string with letter f.

b.   Put braces around the variable name that you want to use inside the string.

 

interpolation.py

first_name = "Sailu"
last_name = "Dokku"
age = 32

message = f"Hi {first_name} {last_name}, you are {age} years old"
print(message)

 

Output

$python3 interpolation.py 
Hi Sailu Dokku, you are 32 years old

 

You can even call the functions on variable inside {}.

 

Example

message = f"Hi {first_name.upper()} {last_name.upper()}, you are {age} years old"

 

interpolation2.py

first_name = "Sailu"
last_name = "Dokku"
age = 32

message = f"Hi {first_name.upper()} {last_name.upper()}, you are {age} years old"
print(message)

 

Output

$python3 interpolation2.py 
Hi SAILU DOKKU, you are 32 years old

 

You can even use ‘format’ method to do string interpolation.

 

 

Syntax

"{} {}".format(variable_name1, varible_name2)

 

Variables are referred by set of braces.

 

interpolation3.py

first_name = "Sailu"
last_name = "D"
age = 32

message1 = "Hi {} {}, you are {} years old".format(first_name, last_name, age)
message2 = "Hi {} {}, you are {} years old".format(first_name.upper(), last_name.upper(), age)

print(message1)
print(message2)

 

Output

 

 

$python3 interpolation3.py 
Hi Sailu D, you are 32 years old
Hi SAILU D, you are 32 years old



 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment