×

How to Convert int to str in Python

How to Convert int to str in Python

In the last article, we studied how we convert a variable with string datatype to integer datatype and discussed different data types available in Python. In this section, we will see the ways & methods that can convert an integer data type to a string data type.

Four ways can help us in the conversion-

  1. Using str()
  2. Using f-string
  3. Using the "%s" keyword
  4. Using. format () function

First, let us discuss how we can convert int to str in python using str()

 int= 15                       #declaration of variable
 print(type(int))
 str_var=str(int)              #converting the data type
 print(type(str_var))
 print(int+15)
 print(str_var+’15’) 
  1. In the first line, we have declared the number 15 as an integer.
  2. To verify its data type, we will apply the type function, it will display the output as- <class ‘int’>.
  3. The next step is to convert our data type from integer to string using the explicit type conversion and assign the string value to a new variable called ‘str_var’.
  4. On checking the data type, we will find that its datatype is an integer. (it will display the output as <class 'str’>.
  5. It’s time to check on what results in the variables int & str_var give when we perform operations on them.
  6. So, when we simply add the variable int with 15 print(int+15), it will display the output as 30.
  7. If we directly add 15 to the variable str_var, it will display an error because of the difference in data types, so we will write 15 as a string here
print(str_var+'15')
  • On running the given program, this print statement would give output as 1515.

Next, let’s have a look at how the same functionality can be performed by using f-string.

F-string in Python is a formatting mechanism that is also known as Literal String Interpolation.

The values declared as a string in Python can be embedded directly in the statement which we want to display using the print statement.

Let’s look at an example that illustrates the working of f-string.

 a='Python'
 b='Tutorial and Example'
 print(f"You will find different concepts of {a} at {b}") 

The f-string technique would replace the variables a and b with their respective values and would display them in the output of the print statement.

 int= 15                      #declaration of variable                                          
 print(type(int))                                               
 str_var=f'{int}'             #converting the data type
 print(type(str_var))                                       
 print(int+20)
 print(str_var+'20') 

On checking the data type, we'll find that the f-string technique converts the datatype of our variable and the output of print(type(str_var)) comes out to be <class ‘str’>.

The outputs that will be obtained after the execution of the last two print statements would be 35 and 1520.

Now, we will see how we can convert an integer to a string using "%s" keyword.

%s keyword performs the following functions-

  1. Performs concatenation of two strings.
  2. It is used to convert any value to a string data type.
  3. It formats a value inside a string.
 int=15                           #declaration of variable
 print(type(int))
 str_var="% s" % int              #converting the data type
 print(type(str_var))
 print(int+10)
 print(str_var+'25') 

On executing the given program, we'll observe that the %s keyword converts the integer data type to a string datatype. This can be verified by using print(type(str_var)).

Last is using. format() function,

Placeholders are used in a print statement when we are using the format function. In the parentheses, we provide the variables that replace these placeholders with their respective values.

Let’s try to understand this with the help of a simple example-

 a=10
 b=20
 add_num=a+b
 print("Sum of {} and {} is {}".format(a,b,add_num)) 

In the given program, we have declared the variables a and b as 10 and 20 respectively. After that to find the sum, we will store the value of a+b in a variable called add_num. Then in the print function, we will provide placeholders which will be replaced by the values of variables a,b, and add_num using the format function.

It can be used in our program in the following way-

 int=15                         #declaration of variable
 print(type(int))
 str_var="{}".format(int)        #converting the data type
 print(type(str_var))
 print(int+10)
 print(str_var+'25') 

The data types of both variables can be verified using the type function. On executing the given program, we will observe that the data type of int is an integer and the data type of str_var is a string.

So, in this article we discussed the methods of converting an integer data type to a string data type using str(), %s keyword, .format(), and f-string.


Related Topics

Python max() function

Python max() function The max() function in Python returns the largest item in an iterable or the largest of two or more arguments. Syntax max(iterable, *[, key, default])               or max(arg1, arg2, *args[, key])   Parameter arg1, arg2, *args: This...

1 minute read.

How to learn python Online

Need to Learn a Programming Language 1. To get a high Paying job We know that Software Engineering is one of the top-paying professions in the world. The top criteria to be...

3 minutes read.

Python Modules

Python Modules The Python module is a collection of definition and statements. It can contain functions, classes, and variables.  Combining the related code into a module makes the code easier to understand and use....

5 minutes read.

How to Open a File in Python with a Path?

File in Python File handling is an important operation; it allows the programmer to access the data in the files, such as text, binary values and excel sheets. The CSV files...

7 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

Python Modules List

Python is like an ocean. If you have been working with Python, you might’ve already heard the word module. When we solve a problem in mathematics, there will be several...

3 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

Python Project Ideas

One of the most widely used programming languages today is Python. This pattern appears set to continue through 2023 and beyond. Therefore, working on some current Python project ideas is the...

10 minutes read.

Weight Conversion GUI using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

Python Comment Block

In this tutorial, we will see what comment blocks mean in Python. Further, we will see the commenting methods supported in Python. We will understand the topics deeply with the...

6 minutes read.

How to Call a Function in Python

How To Call a Function in Python Functions are the well-defined and structured piece of code that is used to implement specific functionality. Calling a function in python is the best...

4 minutes read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.

Python range() function

Python range() function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Syntax range(stop)        or range(start, stop[, step]) Parameter start: It is...

1 minute read.

Conditional Statements in python

In this article, we will learn about conditional statements and how to apply conditional statements in Python. A decision-making statement is another name for a conditional statement. Decision-making is an important...

5 minutes read.

Anaconda python 3.7 download for windows 10 64-bit

Before installing Anaconda, you need to first know what Anaconda actually is. Anaconda is an IDE (Integrated development environment) platform used to code and executes python programs. Anaconda works both online...

3 minutes read.

Python List copy() method

Python List copy () method The list.copy () method returns a shallow copy of the list. Syntax list.copy() Parameter NA Return This function returns the copy for the given list. Example 1 # Python program explaining # the list.copy() method # passing the...

1 minute read.

Python float()

Python float() class The float() class in Python returns a floating point number constructed from a number or string x. Syntax class float([x]) Parameter x: This parameter represents a number or a string that can be converted...

1 minute read.

FOO in 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...

3 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.