Difference between String Concatenation and String Interpolation in Python

in
# String Concatenation
name = "John"
age = 25
print("Hello, my name is " + name + " and I am " + str(age) + " years old.")

# String Interpolation
name = "John"
age = 25
print(f"Hello, my name is {name} and I am {age} years old.")

# String Interpolation with format()
name = "John"
age = 25
print("Hello, my name is {} and I am {} years old.".format(name, age))

# String Interpolation with format() and positional arguments
name = "John"
age = 25
print("Hello, my name is {0} and I am {1} years old.".format(name, age))

# String Interpolation with format() and keyword arguments
name = "John"
age = 25
print("Hello, my name is {name} and I am {age} years old.".format(name=name, age=age))

# String Interpolation with format() and mixed arguments
name = "John"
age = 25
print("Hello, my name is {0} and I am {age} years old.".format(name, age=age))

Comments

Leave a Reply

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

Discover more from Jorge Saldívar

Subscribe now to keep reading and get access to the full archive.

Continue reading