×

How to Convert Int to String in Python?

Every value we use or store in a variable in Python will have a specific data type. It describes the value's nature; based on that, Python will automatically assign a data type. In this article, we will see int-to-string conversion techniques that change an inputted integer value into a string.

Example:

Python supports a variety of data structures, including lists, tuples, dictionaries, and sets, as well as numerous data types for various value sets. Integers deal with numbers and strings that may accept alphanumeric values. To give you an overview of the Python data types, we defined two different values in the example below and tested their data types.

x='It's a Beautiful World.'
y=85
print(type(x))
print(type(y))

Output:

<class  ‘str’>
<class ‘int’>

We could infer from the example that the string data type and integer data types are quite clear. A sentence enclosed in quotations has been assigned to the variable "x." The variable "y" is a straightforward numeric character and illustrates a string data type.

How does Python Convert an Integer to a String?

There are four ways to convert an integer data type in Python to a string data type. They are listed below:

  • Using the method str()
  • With %s string
  • .format() function use
  • F-string usage

1. The str() method

Syntax:

str(integer)

The str() function translates the value supplied in and returns a data type of string. The object can be a string, an int, or a char. If no parameter is supplied, the function returns nothing.

Example:

Let's look at some basic code that converts an int to a string.

#int to string conversion
x = 10
# print out the x variable's data type.
print(type(x))
# make the x variable a string
y = str(x)
# determine and report the y variable's type.
print(type(y))

Output:

<class  ‘str’>
<class ‘int’>

In the procedure above, we have assigned the variable 'x' an integer value of 10, and converted it using Python's str() function, and the resulting 'y' variables returned a string data type.

Example:

The string data type supports various operations, including cutting, replacing, concatenating, and more. Let's talk about a different instance, as illustrated below.

#string value printing code
a = 'Its a beautiful day
print(a[1])
print(a[2:7])

Output:

t
s a b

We have assigned the string "It's a gorgeous day" to the variable in the code above. The sliced first position of the string, which is also a string, is printed in the next line. The string's second and seventh positions have been cut off and printed in the next line. The string data type is simple to use and offers a variety of characteristics.

2. Using %s, convert an integer to a string

Syntax:

"%s" % integer value

Example:

# int to string conversion using %s
a = 5
# print the value and data type of variable a
print(a)
print(type(a))
# convert the integer a into a string and print the value and data type
b = "% s" % a
print(b)
print(type(b))

Output:

5
<class  ‘int’>
5
<class ‘str’>

In the above program, we've given the variable an integer value of 5, and we've printed the value and data type of a. Using the, we changed the integer a to a string b in the following section. In the final step, we printed the b's data type

and verified the outcome. We'll add two integer numbers and transform the result into a string in a subsequent example.

Example:

5
<class  ‘int’>
5
<class ‘str’>

Output:

<class  ‘int’>
<class ‘str’>

We are adding two int values, assigning the result to c, and outputting the data type, as in the previous example. The following step involves checking the data type while converting an int to a string.

3. Converting Int to String Using f- String

Syntax:

f’{integer_value}’

Example:

# f-string is used to convert ints to strings.
a = 5
print(type(a))
b = of{a}'
print(type(b))

Output:

<class  ‘int’>
<class ‘str’>

4. Using. Format, convert an integer to a string () Method

Syntax:

‘{}’.format(integer_value)
#Using the. Format () method, convert an int to a string.
name = "Bala"
age = 26
# using the Method. format()
print("{name} is {age} years old".format(name=name, age=age))

Output:

Bala is 26 years old

The string "Bala" has been allocated to the name variable in the code above, and the integer value of 26 has been assigned to the age variable. The age variable will be converted to a string using the. Format () method in the following step, and the string will then be printed as displayed in the output.

Example:

In the example below, we have received two string values as input, added them, and then printed the result's data type.

#code to sum of two input strings and convert it to the int value
x = input('Enter first integer value:\n')
x=int(x)
y = input('Enter second integer value:\n')
y=int(y)
sum_inputs=x+y
print('sum of Inputs:{}'.format(sum_inputs))
print(type(sum_inputs))

Output:

Enter first integer:
16
Enter second integer:
33
Sum:
49
<class ‘int’>

In the above code, we have declared the two inputs, x and y, to be strings, then summed them, converted them to integer values, and displayed the total as output. If we performed an addition operation without converting the numbers into an int, the output would be as we would expect.

Enter first integer:
111
Enter second integer:
33
Sum:
11133
<class ‘str’>

Since we declared two string values in the output above and performed a sum operation on them because they are string values, the result is merely a combination of the two strings; no mathematical action is carried out because it is a string value.


Related Topics

Python Printf Style Formating

String objects have one special implicit activity: the % administrator (modulo). This is otherwise called the string designing or interjection administrator. Given design % values (where configuration is a string),...

3 minutes read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.

Python Program to Find the Greatest Among Three Numbers

Python Program to find the greatest among three numbers We have many approaches to get the largest of three numbers, and here we will discuss a few of them. This python...

2 minutes read.

Python String rfind() method

The string. rfind() method in Python returns the highest index in the string if the substring sub is found else it returns -1 if the substring is not found. Syntax string.rfind(sub [,start [,end]]) Parameter sub: This parameter...

2 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

Introducing modern python computing in simple packages

Python is the language for newly evolving technologies and has become one of the most popular computer languages in the world. Python is used in everything right from a simple...

3 minutes read.

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

Python program to find the area of the triangle

Python program to find the area of the triangle This article will discuss how to find the area of a triangle in Python with all three given sides. The area of...

2 minutes read.

Python Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.

Mrcnn Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

Python String decode() method

Python String decode() method The string.decode() method decodes the string using the codec registered for encoding. Default encoding is the current default string encoding. It may raise errors to set a different error handling...

1 minute read.

Check if the directory exists in Python

To prevent any error, while loading or editing a file, we first have to check that the directory or the file exists or not. This is also done to prevent...

5 minutes read.

Python pow() Function

Python pow() Function The pow() function in Python return the parameter ‘x’ to the power ‘y’ and if the parameter ‘z’ is present, it returns x to the power y, modulo z (computed more efficiently than pow(x, y) % z). Syntax pow(x, y[, z]) Parameter x: This parameter represents the base...

1 minute read.

How to comment multiple lines in python?

How to comment multiple lines in python There are two qualities that come up with every good and successful programmer- i) Indenting the code ii) Using comments in the code Let us see how...

4 minutes read.

Python program to print array element present at even position

Python program to print array element present at even position In this program, we'll see a Python program that prints the elements of an array that are in even positions. We...

1 minute read.

Python tokens and character set

In this tutorial, we will understand what are character sets used in python and what is meant by python tokens and we will further discuss the type of tokens being...

4 minutes read.

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples. Any variable holds a value in...

4 minutes read.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

Python ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.