How to convert or concatenate integer with string variable in Python?

Convert int to str. Simple way to concatenate integer and string variables – Python. 

In some cases, you have to concatenate integer variables to string variables in your Python script. You can not do this by simply using the (+) sign. In this post I am going to explain the possibilities on how to concatenate integer with string variable in Python. For this you need to convert the integer to string first.

What are the ways to convert integer to string variable in Python?

  1. str()
  2. Using “
  3. repr()

Python is a good and simple language for SysAdmins automation tasks. See the Index page and read more about Python.

See more about Variables and Types – Python

I am using iPython for demonstration.

string = "Wiki's age is: "
age = 18

print (string + age)

Will get error. Please see the screenshot.
Int to str Python
Int to str Python

Solution

So, we need to convert the integer to string. Then we can print both as string! You can do it in different ways. Please see the examples pasted below:

How to Convert Int to String in Python?

1. Using function str()

string = "Wiki's age is: "
age = str(18)

print (string + age)
Int to str Python
Int to str Python

2. Using backtick (“)

Yeah, it’s possible to concatenate integer with string using backtick option. Please see the example added below:

age2 = 20

print (string + `age2`)
Wiki's age is: 20
Int to str Python
Int to str Python

In this example the first part is string and age2 is an integer variable.

3. Using function repr()

This is same as str() function. See the examples:

age3 = repr(21)

print (string + age3)
Wiki's age is: 21
Int to str Python
Int to str Python

That’s it!!

How to update a Docker image with new changes?

Yeah, we all know, the Docker image is the core part of your Docker container. The container works based on this Image. Docker image can be built using many ways.

We can build many containers from a single image. An image is a combination of a file system and parameters.

Once the container is launched using an image, you can make changes on that container. Like, you can create new files, you can install new modules, packages etc.. These changes will persist on the container as long as it exists. READ MORE..

 

Post navigation

Arunlal Ashok

Cloud Infrastructure / DevOps Engineer. I know her (Linux) since many years. Linux lover. Like to play on Linux console. I started this blog to share and discuss Linux thoughts.

Always happy for an open discussion! Write to arun (@) crybit (dot) com. Check about me for more details. About this blog and our strong members, check The team CryBit.com

One thought on “How to convert or concatenate integer with string variable in Python?

Leave a Reply

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