How to concatenate String and Int in Python
Python supports string concatenation using + operator. However, in Python, if you try to concatenate string and int using + operator, you will get a runtime error.
Lets see what happens when we try to concatenate string and int with + operator.
>>> a = 'one' >>> b = 1 >>> print(a + b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str
You will get a similar kind of error, if you try doing this.
To concatenate string and int using + operator, we need to use str()
to convert the int explicitly to str. Only concatenation between str and str is possible.
>>> a = 'one' >>> b = 1 >>> print(a + str(b)) one1 >>>
Using % operator
a = 'one' b = 1 print("%s %s" %(a, b))
Using format()
>>> a = 'one' >>> b = 1 >>> >>> print("{}{}".format(a, b)) one1
Using f-string:
>>> a = 'one' >>> b = 1 >>> print(f'{a}{b}') one1 >>>
Subscribe
Login
Please login to comment
0 Discussion