F- String — An Improved String Formatting in Python

Photo by Carlos Alberto Gómez Iñiguez on Unsplash

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.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Print X array elements closest to the Kth smallest element in the array

https://bit.ly/38SoWXr

Value Iteration on Python Explained (part 2)

Memory Profiling in Python

Secure microservice-to-microservice communication across Kubernetes clusters using a private…

A Few Quick Tips to Make PhpStorm Faster

Questions with Swupnil Sahai, Co-Founder and CEO of SwingVision, former Tesla Computer Vision…

The 3 best ways to center an element in css

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sachinjose

Sachinjose

More from Medium

Restoring objects from Glacier to S3 using Batch Operations (using Python boto3)

Identifiers in Python

How to Send SMS to Mobile Number using python

tqdm in While loops