×

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

How to convert integer to float in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

5 minutes read.

The Calendar Module of Python

The calendar module provides calendar features, including printing functions for a specific month or year. Default is the first day of the week on Monday and the last day on Sunday...

3 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

Python Tuple Methods

Python Tuple Methods Python has two built-in methods that are used for tuples. The following are the two methods: Method Description count() The tuple.count() method in Python returns the number of times a...

1 minute read.

Write a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

5 minutes read.

Python divmod() function

Python divmod() function The divmod() function in Python returns a tuple containing the quotient  and the remainder when parameter ‘a’ (divident) is divided by parameter ‘b’ (divisor). Syntax: divmod(a, b) Parameter a: This parameter represents a number you...

1 minute read.

Python MongoDB Tutorial

An Introduction to MongoDB MongoDB is a document-oriented database application. It is an Open-source and platform-independent program. MongoDB is similar to few NoSQL databases that store the data in the documents...

17 minutes read.

Type casting in Python

Introduction Type Casting is defined as the method of converting the variables/values data type into a certain data type for matching the operation needed to be performed by the users. This...

4 minutes read.

Cx_Oracle Python with Example

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 Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

Data Structures and Algorithms Using Python | Part 1

Data Structures: Data Structure is defined as a way to organize and store the data so that we can access the data and work more efficiently. Data structures also describe the...

18 minutes read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.

Python len() function

Python len() function The len() function in Python  returns the number of items in an object. Syntax len(s) Parameter s: This parameter represents a sequence (such as a string, bytes, tuple, list, or range) or...

1 minute read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

Python MySQL Delete Operation

Python MySQL Delete Operation: Like the update operation where we were updating required field from a SQL table, we can also delete an entry from the table which we have...

4 minutes read.

PyDev with Python IDE

What is IDE? Integrated Development Environment is the abbreviation of IDE. It is a coding tool that automates code editing, finding errors and testing. IDE combines all the developer tools into...

3 minutes read.

Python Classification

Identification and grouping of items or concepts into specified categories this process is known the classification. Data can be separated and sorted in data management according to predetermined criteria for...

6 minutes read.

Python Read CSV file

The CSV stands for “comma-separated value,” which is defined as a simple file format that is used to store data into a tabular form such as a database or spreadsheet. It is...

7 minutes read.

Python program for perfect number

Python program for perfect number Before writing any program for a given problem, we have to understand the problem for which we are creating a solution program. So, let's understand what...

2 minutes read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.