Python Library Tips: f.strings


f.strings

In Python you can format string in a variety of ways.We learned how to use a %format technique in last post. In Python version 3.7 introduced f.string .

f/F strings are literals begins with letter f/F and It uses { }, curly braces for replacement of expressions with their values

spyder_version=3
python_version=2.7
print(f'I am using Spyder ID {spyder_version} with Python {python_version}')

#Output
I am using Spyder ID 3 with Python 2.7

Arbitrary expression

F"{10*10}"

#Output
100

Function call

We can also call function inside f.strings.

def multi(x,n):
    return x*n
f'{multi(2,2)}'

Multipleline

f-strings are faster than % formatting because they ares constants while f.string expressions are evaluated at runtime.

Also it is possible compose f.strings in multiple line. All strings must begin with ‘f/F’.

>>topic='panda frames'
>>lang='python'
>>version =3.8
>>say=(f'I want to use {topic}'
  f' in {lang}'
  f' version {version}')

>>say
Out[20]: 'I want to use panda frames in python version 3.8'

It can also be rewritten using ‘\’

>>say=f'I want to use {topic}' \
f' in {lang}' \
f' version {version}'

1 thought on “Python Library Tips: f.strings

  1. Pingback: Python Library Tips: timedelta | Manoj's Developer Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.