Python Concatenation and Formatting

Most used concatenation and formatting in python 3.x.
For reference, the ‘>>>’ characters indicate where the interpreter is requesting a command.

Photo by Shahadat Rahman on Unsplash

Concatenation

In string concatetion, we can use ‘+’ or comma separator

>>> print('apple' + 'banana')
applebanana

In string and other datatype (int), can not directly use ‘+’ to concate and print

>>> print('apple'+3)
Traceback (most recent call last):
File '', line 1, in
----> print('apple'+3)
TypeError: can only concatenate str (not "int") to str

try to convert int to str, or use comma separated.

>>> print('apple'+str(3))
apple3

Formatting with %

>>> a = 'apple'
>>> b = 'banana'
>>> print('This is %s and %s' % (a, b))
This is apple and banana

%s indicate the datatype is string

>>> a = 'apples'
>>> n = 3
>>> print('I have %i %s' % (n, a))
I have 3 apples

%i indicate the datatype is int

>>> a = 2.2145125621245
>>> print('Shorter float number %.2f' % a )
Shorter float number 2.21

%.2f indicate the datatype is with 2 digits after dot

Formatting with Curve Bracket {}

>>> a = 'apple'
>>> b = 'banana'
>>> print('This is {} and {}'.format(a, b))
This is apple and banana

Software Engineer