Learn Python - 6 [string formatting]

in #python6 years ago

Image uploaded from iOS.jpg
What if you want to put a variable into a string or text? Generally, this is called string formatting. Let's start with an example:

>>> movie = 'Inception'
>>> text = 'We are going to watch %s movie.' % movie
>>> text
'We are going to watch Inception movie.'
>>> print(text)
We are going to watch Inception movie.

What if you want to variables in the string:

>>> time = '9.15pm'
>>> text = 'We are going to watch %s movie at %s.' % (movie, time)
>>> text
'We are going to watch Inception movie at 9.15pm.'

You can put as much as variables into a text just you need to surround variable names with parentheses % (one, two, three, ...).

If you want to put a number into the string instead of using %s you will use %d. d stands for digit and s is for a string.

>>> a_number = 17
>>> text = 'You guessed %d' % a_number
>>> text
'You guessed 17'

Float numbers use %f:

>>> pi = 3.141592
>>> text = 'PI number %f' % pi
>>> text
'PI number 3.141592'

If you want only 2 digits after . then use %.2f:

>>> text = 'PI number %.2f' % pi
>>> text
'PI number 3.14'

All these formats are considered old style and don't recommend for the future. So what should you use? The answer is format().

>>> one = '1'
>>> two = '2'
>>> '{}, {}'.format(one, two)
'1, 2'

format(one, two) works same as %(one, two) but its more readable and has much more power.
You can pass variables and change the order of them in the string:

>>> one = '1'
>>> two = '2'
>>> '{1}, {0}'.format(one, two)
'2, 1'
>>> '{:.3}'.format(pi)
'3.14'

More for python3.6
Python3.6 version and later has f'' style so you can format string as follows:

>>> f'Pi number {pi}'
'Pi number 3.14159265359'

as you see we can use the variable name inside the string and its replaced by the value. We can do the same with format():

>>> 'Pi number {pi}'
>>> 'Pi number {pi_number}'.format(pi_number=pi)
'Pi number 3.14159265359'

What if you want a string to repeat for 5 times or any number you like:

>>> 'steem ' * 5
'steem steem steem steem steem '

In the future, we will talk about string formatting so its not the end for string formatting.

Sort:  

Hey @mtndmr, great post! I enjoyed your content. Keep up the good work! It's always nice to see good content here on Steemit! Cheers :)

@exxodus thank you for your nice comment. I will do my best :)