Python Concatenation and Formatting

Photo by Shahadat Rahman on Unsplash
>>> print('apple' + 'banana')
applebanana
>>> print('apple', 'banana')
apple banana
>>> print('apple'+3)
Traceback (most recent call last):
File '', line 1, in
----> print('apple'+3)
TypeError: can only concatenate str (not "int") to str
>>> print('apple'+str(3))
apple3
>>> print('apple', 3)
apple 3
>>> a = 'apple'
>>> b = 'banana'
>>> print('This is %s and %s' % (a, b))
This is apple and banana
>>> a = 'apples'
>>> n = 3
>>> print('I have %i %s' % (n, a))
I have 3 apples
>>> a = 2.2145125621245
>>> print('Shorter float number %.2f' % a )
Shorter float number 2.21
>>> a = 'apple'
>>> b = 'banana'
>>> print('This is {} and {}'.format(a, b))
This is apple and banana
>>> a = 'apples'
>>> n = 3
>>> print('I have {} {}'.format(n, a))
I have 3 apples
>>> a = 2.2145125621245
>>> print('Shorter float number {:.2f}' .format(a))
Shorter float number 2.21

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store