TUTORIAL
String Formatting with Python-f-String, and why you should start using it
So, What is String Formatting?
String Formatting (sometimes also referred as “String Interpolation”) is a technique for embedding or inserting variables into placeholders in a Python String object.
Three ways to format a String in Python:
1. Old school %s String Formatting
2. A better string formatting: String.format()
3. f”string” method - why it’s the best for String formatting in Python compared to .format() and %s
name = "Frank"
age = 24
profession = "Python Dev"
language = "Python"
person = dict(name="Frank", age=24,
profession="Python Dev", language="Python")
1. %s string formatting
print("My name is %s and I'm a %s. I'm currently being %s and my favourite language is %s" \
% (name, profession, age, language))
My name is Frank and I'm a Python Dev. I'm currently being 24 and my favourite language is Python
2. str.format() - string interpolation
# a.) Interpolation with empty curly braces
print("My name is {} and I'm a {} and I'm {} \
years old and My favourite lan is {}".format(name, profession, age, language))
My name is Frank and I'm a Python Dev and I'm 24 years old and My favourite lan is Python
# b.) Interpolation with tuple indexing
print("My name is {3} and I'm a {0} and I'm {1} \
years old and My favourite lan is {2}".format(profession, age, language, name))
My name is Frank and I'm a Python Dev and I'm 24 years old and My favourite lan is Python
# c.) Interpolation with dictionary key-value mapping
print("My name is {name} and I'm a {profession} and I'm {age} \
years old and My favourite lan is {language}".format(**person))
My name is Frank and I'm a Python Dev and I'm 24 years old and My favourite lan is Python
3. Python f-string Formatting
print(f"My name is {name} and I'm a {profession} and I'm {age} and I love {language}")
My name is Frank and I'm a Python Dev and I'm 24 and I love Python
Any inner curly braces as placeholders in a f-string are Python run-time !!!
native Python code can be executed!!!
# Convert the parameter to a String
def stringfy(value):
return str(value)
## Run a function in a f-string placeholder
print(f"Hello, my age is stringfied here as {stringfy(value=24)}")
Hello, my age is stringfied here as 24
## Other operations: dictionary key indexing in f-string placeholders.
print(f"My name is {person['name']} and I'm a {person['profession']}")
My name is Frank and I'm a Python Dev