Python Concatenate String and int

We will develop a Python program to concatenate string and int using the native method, str() function, format(), and % operator. If the string is “Know Program” and the number is 100. Then, after concatenation string will be “Know Program 100”.

How to Concatenate String and int in Python

We will take the string and the integer while declaring the variables. Then, directly print the concatenate string and int using the print() function.

# Python program to concatenate string and int

# take integer
string = 'Know Program'

# take integer
integer = 100

# concatenate string and int
print(string, integer)

Output:-

Know Program 100

In python, we will add two integer, floating-point numbers, and string concatenate using the + operator. But, if you try to concatenate string and integer using the + operator then, the python program will get a Runtime Error.

string = 'Know Program'
integer = 100

print(string + integer)

Output:-

Traceback (most recent call last):
File “main.py”, line 10, in
print(string + integer)
TypeError: Can’t convert ‘int’ object to str implicitly

Python Concatenate Strings and int

The str() method returns a string, which is considered an informal or nicely printable representation of the given object. In this program, the str() function converts the integer to string. Then, concatenate string using + operator.

# Python program to concatenate string and int

# take integer
string = 'Know Program '

# take integer
integer = 100

# concatenate string and int using str()
print(string + str(integer))

Output:-

Know Program 100

Concatenate String and int in Python

Using format() function

The built-in format() method formats the specified value(s) and insert them inside the string’s placeholder. The placeholder is defined using curly brackets: {}. The format() method returns the formatted string.

# Python program to concatenate string and int

# take integer
string = 'Know Program '

# take integer
integer = 100

# concatenate string and int using format()
print('{}{}'.format(string, integer))

Output:-

Know Program 100

Using % format specifies

Python uses C-style string formatting to create new, formatted strings. The “%” operator is used to format a set of variables enclosed in a “tuple” (a fixed size list), together with a format string, which contains normal text together with “argument specifiers”, special symbols like “%s” and “%d”.

# Python program to concatenate string and int

# take integer
string = 'Know Program '

# take integer
integer = 100

# concatenate string and int using % format()
print('%s%s' %(string, integer))

Output:-

Know Program 100

Also See:-

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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