Formatting text and a variables in python

Photo by Jon Tyson on Unsplash

Formatting text and a variables in python

f'strings and str.formart and other

·

2 min read

We use print function to print some stuff whatever you want. Sometimes we search for different ways to print a string which has some text and variables. This list is a compilation of some of the ways to format the print statement which suits to our needs.

Lets take an example which prints the estimated sales for a month. Below is a static method to do that which is not preferred when we have variable data, which prints this 'Estimated sales for month January = 1830 units'. we need to write a print statement so it can print for other variable data. print('Estimated sales for month January = 1830 units') These are the most basic ways to get what we want. we can separate the strings as shown below. We can use this for some random stuff however the code looks messy. ``` month = 'January' est = 1830

Default

Printing all types of data separated by commas.

print('Estimated sales for month',month,'=',est,'units')

Concatenating Strings

Printing data by concatenating strings.

print('Estimated sales for month '+month+' = '+str(est)+' units')

Using str.format

We can use `format()` to format strings as shown below. The first line places values into the string based on the order of variables, it's important to have them in order as they appear on string. The second line shows a way to index the values. this is very useful when we want to repeat these values in the string. we can just index them. Instead of using index, we can use names as shown in line 3. This can make code readable, and makes it easy to make changes.

print('Estimated sales for month {} = {} units'.format(month,est))

print('Estimated sales for month {0} = {1} units'.format(month,est))

print('Estimated sales for month {mname} = {sales} units'.format(mname = month,sales = est))

Using % operator

The % operator in python for strings is used for something called string substitution. This is similar to printf in C language.

# method 4
print('Estimated sales for month %s = %d units'%(month,est))

print('Estimated sales for month %(mname)s = %(sales)d units'%{'mname':month,'sales':est})

Using f'strings

Python 3.6 has newly introduced a new way to format strings called Formatted String Literals. The string starts with the prefix f. You can do inline arithmetic operations with this. This makes the strings more readable.

print(f'Estimated sales for month {month} = {est} units')

Did you find this article valuable?

Support Dataset Stories by becoming a sponsor. Any amount is appreciated!