Format Strings in Python

We have very powerful method str.format() in python through which you can do variable substitutions and value formatting.
Let’s understand the usage of format with couple of examples.

 
ex1

Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str.format(). The value we want to put into the placeholders and concatenate with the string passed as parameters into the format function.

format() method takes any number of parameters. But, is divided into two types of parameters:
Positional parameters – list of parameters that can be accessed with index of parameter inside curly braces {index} ,See the example below.

ex2

Keyword parameters – list of parameters of type key=value, that can be accessed with key of parameter inside curly braces {key}
See the example :
ex3

we have another method of formatting string literals , as shown below:

ex6

You could also call functions as shown below:

ex7

Hope you have enjoyed the post,please share your comments

Advertisements

One thought on “Format Strings in Python

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