Python concatenate string and int

This tutorial teaches how to concatenate string and int in Python

In other languages such as Java, C++, etc, you can concatenate string and int using + operator, but you can not do the same in python.

How to concatenate string and int in Python

Let’s first try to use + operator to concatenate string and int.

Output:

There are multiple ways to concatenate string and int in Python.

Using str()

Best way to convert intOne to str using str() function.
Here is an example.

Output:

one1

Using format()

You can also use format() function to concatenate string and int.
Here is an example.

Output:

two2

Using % operator

You can also use % operator to concatenate string and int.
Here is an example.

Output:

three3

Using repr() operator

repr() provides printable representation of the object.
Here is an example.

Output:

Six6

Using f-strings

You can also use f-strings operator to concatenate string and int from python 3.6 onwards.
Here is an example.

Output:

four4

Print String and int together

If you just wanted to print String and int together, you can use print() with sep="".
Here is an example.

Output:

Five5

Why can’t we use + operator to concatenate string and int

In python, + can be used for adding two numbers or concatenate the sequences.

As a rule, python does not convert objects implicitly from one to another while using the operator, so it may be confusing what exactly you want to do with + operator.

2 + ‘3’ can be either ’23’ or 5, so python does not support + operator to concatenate string and int.

You can not concatenate sequences of different types using + operator in Python.

Output:

As you can see, you can not concatenate list and set using + opertor.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *