Skip to content

Instantly share code, notes, and snippets.

@ofelix03
Created March 2, 2021 12:56
Show Gist options
  • Save ofelix03/3570830f00a825b3fabd3f07ba39c99d to your computer and use it in GitHub Desktop.
Save ofelix03/3570830f00a825b3fabd3f07ba39c99d to your computer and use it in GitHub Desktop.
Comparing interpolation methods (f-strings, Str.format and %-formatting string)
# Let starts with defining some variables
first_name = "Felix"
middle_name = "Albert"
last_name = "Otoo"
age = 28
profession = "Software Engineer"
# % formatting string
# Ex. 1 Using position placeholders
print("This is %s %s %s. He is %s years old. He is a %s" %(first_name, middle_name, last_name, age, profession))
# Ex. 2 Using named placeholders
print("This is %(first_name)s %(middle_name)s %(last_name)s. He is %(age)s years old. He is a %(profession)s" %{"first_name": first_name, "middle_name": middle_name, "last_name": last_name, "age": age, "profession": profession})
# Str.format()
# Ex. 1 Using position arguments
print("This is {} {} {}. He is {} years old. He is a {}".format(first_name, middle_name, last_name, age, profession))
# Ex. 2 Using keyword arguments
print("This is {first_name} {middle_name} {last_name}. He is {age} years old. He is a {profession}".format(first_name=first_name, middle_name=middle_name, last_name=last_name, age=age, profession=profession))
# f-string
print(f"This is {first_name} {middle_name} {last_name}. He is {age} years old. He is a {profession}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment