How to concatenate integer with string variable in 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.
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.
You can do it in different ways. Please see the examples pasted below:
1. Using function str()
string = "Wiki's age is: " age = str(18) print (string + age)
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
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