Converting Integer to String in Python

Quick Fix: Python’s built-in str(x) method converts an integer object x to a string object by using the x.__str__() method.

❖ Introduction

Problem Formulation: Given a string object in Python, what are the ways to convert it to an Integer type?

Example:

# This is an integer
x = 13
print("x is of type", type(x))
# Converting integer to string
y = str(x)
print("y is of type", type(y))

Output:

x is of type <class 'int'>
y is of type <class 'str'>

Let us have a look at an example where converting an integer becomes a defining factor in your code.

Scenario: Concatenate a string and an integer.

version = 3
lang = 'Python'
print(lang+version)

# Desired Output: Python3

Actual Output:

Traceback (most recent call last):
  File "D:/PycharmProjects/PythonErrors/int2string.py", line 3, in <module>
    print(version+lang)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Explanation: The usage of the + operator to concatenate a string and integer is not allowed in Python. Thus, Python throws a TypeError: unsupported operand type(s) for +: 'int' and 'str' in this case.

The solution to this problem is to convert the integer object to a string object and then concatenate the two strings as shown in the solution below.

Solution:

version = 3
lang = 'Python'
print(lang+str(version))


# Output: Python3

Before moving on to the solutions, I highly recommend you to go through the type conversion techniques explained in this tutorial.

Now, without further ado, let us dive into the solutions to our mission-critical question – “How to convert an integer to a string in Python?

🖋️ Method 1: Using The str() Method

Python’s built-in str(x) function converts the object x to a string using the x.__str__() method or, if non-existent, the repr(x) built-in function to obtain the string conversion.

  • The str() method returns a string type of an object. The object can be char, integer, etc. The str() method returns a string type of an object. The object can be char, integer, or a string.

Syntax:

str(object)
Python str() Function Built-in -- Explanation

Example:

num_int = 2500
num_str = str(num_int)
print("num_str: ", num_str)
print("Type of num_float: ", type(num_int))
print("Type of num_str: ", type(num_str))

Output:

num_str:  2500
Type of num_float:  <class 'int'>
Type of num_str:  <class 'str'>

🖋️ Method 2: Using The format() Function

We can use the format() method in Python, for converting integers to strings. This method permits you to set placeholders inside a string and then convert any other data type (integer, float) to a string and fill the placeholders. Curly brackets ‘{} ’ are used to define the placeholders.

Syntax

"{}" .format (int)

Example:

# This is an integer
y = 20
print("The value of y is", y)
print("Initially the number is of type", type(y))

# Converting integer to string using format()
y = "{}".format(y)
print("The number is of type", type(y), "after conversion.")

Output:

The value of y is 20
Initially the number is of type <class 'int'>
The number is of type <class 'str'> after conversion.

🖋️ Method 3: Using String Conversion ‘%s

Python utilizes two unique styles of string formatting: the oldest style that depends on the modulo operator (%), and the more up-to-date Python 3 style that utilizes the format function. (As seen in method 2).

  • Python’s old standard string conversion method uses the modulo operator (the percent sign %) as a unique symbol to demonstrate the various types of formats.
  • The conversion specifiers, for example, %s and %d show up in the format string as placeholders.
  • These specifiers direct how the operation will format the values.
  • %s is used for string conversion.

Example:

# This is an integer
no = 2
print("Initially the value of the number is", no)
print("The number is of type", type(no))

# Converting integer to string using %s
conv = "% s" % no
print("The number is of type", type(conv), "after conversion.")

Output:

Initially the value of the number is 2
The number is of type <class 'int'>
The number is of type <class 'str'> after conversion.

🖋️ Method 4: Using f-strings

f-strings are supported in Python 3.6 or higher versions. It is represented by string literals that have an f as a prefix and curly braces containing the expressions. The variables in the expression get replaced by the values during evaluation at runtime.

Syntax:

f'{ int }'

Example:

# This is an integer
x = 50
print("The value of the number is", x)
print("The number is of type", type(x))

# Converting integer to string using f strings
y = f'{x}'
print("The value of the number remains", y)
print("The number is of type", type(y), "after conversion.")

Output:

The value of the number is 50
The number is of type <class 'int'>
The value of the number remains 50
The number is of type <class 'str'> after conversion.

🖋️ Method 5: Using a Custom Method

Another workaround, that deserves to be mentioned is a user-defined custom method that converts the integer object to a string object as shown in the following example.

Example:

def convert(x, type_):
    x = type_(x)
    return x
num = 25
print("Initially type of num : ", type(num))
print("Type of num after conversion: ", type(convert(num, str)))

Output:

Initially type of num :  <class 'int'>
Type of num after conversion:  <class 'str'>

❖ Conclusion

Thus, the following methods can be used to convert an integer to a string in Python:

  •  The str() built-in method.
  •  The format() Function.
  •  String Conversion using ‘%s‘.
  •  Using f-strings.
  •  Defining a Custom function.

I hope this article helped you. Please subscribe and stay tuned for more interesting articles in the future.

Authors
🤵
SHUBHAM SAYON
👩
RASHI AGARWAL

Recommended Course:

  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.
The Complete Guide to PyCharm

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!