Python Library Tips: str.format


str.format()

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 2.6 introduced str.format() function which is an improvement over % formatting.

It uses { }, curly braces for replacement fields

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

#Output
I am using Spyder ID 3 with Python 2.7

You can access variable using digits starting from {0}-{n} as follows

spyder_version=3
python_version=2.7
print('I am using Python {1} and Spyder IDE {0} for data science ' .format(spyder_version,python_version))

#Output
I am using Python 2.7 and Spyder IDE 3 for data science

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.