F- String — An Improved String Formatting in Python

Sachinjose
2 min readJun 30, 2021

Data can be printed in a human-readable form or written to a file for our reference. String formatting helps us to embed variables into strings.

There are multiple ways to achieve this, such as the modulo operator (%), string concatenation, and the string’s format().

Formatted string literals, also known as f-strings, are an efficient method for string interpolation. F-strings are evaluated at runtime and then formatted using the __format__ protocol.

Syntax: Add the letter f before opening the quotes and place your variables inside curly braces.

name = “Buddy“print( f” Hello {name}. Good Morning “ )

In this article, we will go over some tricks to use f-strings more efficiently.

1. Numeric and String Formatting

name = “Buddy”
print( f” Hello {name}. Good Morning “ )
Output : Hello Buddy. Good Morningsample_list = ["first", "last", "address", "age"]
print(f"{sample_list=}")
Output : sample_list=['first', 'last', 'address', 'age']

2. MultiLine Strings

data = “for our reference”
string = ”Data can be printed in a human-readable " \
f"form or written to a file {data}. “ \
“String formatting helps us to embed variables " \
"into strings.“
print(string)
Output : Data can be printed in a human-readable form or written to a file for our reference. String formatting helps us to embed variables into strings.

3. Decimal truncation

decimal_number = 98.23456
print(f”2 digits: {decimal_number : .2f}")
print(f"4 digits: {decimal_number : .4f}”)
Output : ‘2 digits: 98.23; 4 digits: 98.2345’

4. Separators to big numbers

number = 1234561234567899876
print(f”{number:,d}”)
Output : 1,234,561,234,567,899,876

5. Python Expressions

sample_list = [“first”, “last”, “address”, “age”]
print(f”Length of list is {len(sample_list)}”)
Output : Length of list is 4string = "first name"
print(f"Converting to upper case {string.upper()}")
Output : Converting to upper case FIRST NAMEprint(f'{(lambda x: x*3)(10)}')
Output : 30

6. Perform an if-else verification

gender = “she”
print (f”Hello {‘Sir’ if gender == ‘male’ else ‘Madam’}. Welcome”)
Output : Hello Madam. Welcome

7. Execute functions

def square(num):
return num ** 2
print(f”The square of number is {square(2)}”)Output : Hello Madam. Welcome.

Conclusion

In this article, We have gone through some tricks that we can leverage when using string formatting.
I hope you guys will find this article informative & helpful for you.
Thank you for reading. Please let me know if you have any feedback.

--

--