Convert Integer to String in Python

Last updated by Dipen Dadhaniya on Sep 25, 2024 at 10:58 PM
Contents

Knowing how to use and manipulate strings is an essential skill for any programmer, regardless of the coding language you use. This includes the ability to convert data of other types, like integers or float type numbers, into strings. Sometimes, while solving problems, you might have to output/store a string that must contain, as part of the string, a piece of current, updated information stored in some integer variable.

For example, the string may store the number of new sign-ups to a website that day, the number of units of electricity used till now for this month, etc. In such cases, the conversion skills we learn in this article will come in handy.

If you are preparing for a tech interview, check out our technical interview checklist, interview questions page, and salary negotiation e-book to get interview-ready! Also, read Python String join() Method, Sum Function in Python, and How to Read & Write Files in Python (Guide)|Interviewkickstart for more specific insights and guidance on Python concepts and coding interview preparation.

Having trained over 9,000 software engineers, we know what it takes to crack the most challenging tech interviews. Since 2014, Interview Kickstart alums have landed lucrative offers from FAANG and Tier-1 tech companies, with an average salary hike of 49%. The highest ever offer received by an IK alum is a whopping $933,000!

At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.

Want to nail your next tech interview? Sign up for our FREE Webinar.

In this article, we’ll cover:

  • How to Convert Integer to String in Python
  • Example — Concatenating a String and an Integer
  • Concatenating Strings and Integers While Avoiding Conversions
  • Interview Questions on Converting Integer to String in Python
  • FAQs on Converting Integer to String in Python

How to Convert Integer to String in Python

There are many in-built tools in Python that facilitate the conversion of an Integer to a String. Note that Python does not support type coercion or any implicit conversion, so we must do it explicitly. Let us look at some of the ways we can convert an Integer to a String in Python. We will use the type() function to check the type of data we’re dealing with before and after attempting conversion.

By Using str() Function

The str() function is an in-built function in Python that converts an object into a String by internally calling the __str__() method. You can also use __str__() instead of str() directly, but using special methods, which have the format __x__() directly, is generally discouraged. The str() function takes three parameters:

  • The Object: The object to be converted into a string. For the purposes of this discussion, it will be an int object. But even if the object provided is not an integer or string, Python will not give an error. And if an object is not passed as a parameter, str() will return an empty string.
  • Encoding: The object’s encoding type is mentioned in this parameter, as shown in the syntax below. The default encoding is UTF-8. You can skip providing this detail if unnecessary.
  • Errors: This parameter contains specific details on what to do if the encoding fails. You can skip providing this information if you don’t need to handle the errors in a specific way.

Here’s the syntax to help you understand the format better:

str(object, encoding=encoding, errors=errors)

Let us look at an example to see how it works:

int_to_convert = 10

# printing the type of int_to_convert variable

print(type(int_to_convert))

print(int_to_convert)

 

# converting the number int_to_convert to string

int_converted_via_str = str(int_to_convert)

 

# checking the type of int_converted_via_str

print(type(int_converted_via_str))

print(int_converted_via_str)

Output:

<class ‘int’>

10

<class ‘str’>

10

By Using “%s” Keyword

We can also achieve this conversion from integer to string using the “%s” keyword. This method first converts the object type to a string and then replaces the occurrence of “%s” in the string. It is also used to add a string within another string.

Example:

int_to_convert = 10

# In this example, int_to_convert will be converted into a string

# and will replace the occurrence of “%s” in the passed string.

 

# checking the type of int_to_convert

print(type(int_to_convert))

print(int_to_convert)

 

# converting the number int_to_convert to a string

int_converted_via_s = “%s” % int_to_convert

print(type(int_converted_via_s))

print(int_converted_via_s)

<class ‘int’>

10

<class ‘str’>

10

By Using .format() Function

Yet another way to convert an integer into a string in Python would be using the format function. The format function takes two parameters: The value to format and the format specification on how the value needs to be formatted.

This format specification involves using a placeholder position {} into which the desired value(s) must go. For more information on the format function, check out our page on Python Format Function.

Here’s an example of converting integer to string in Python using format() function:

int_to_convert = 10

 

# checking type of int_to_convert

print(type(int_to_convert))

print(int_to_convert)

 

# converting int_to_convert to string using format

int_converted_via_format = “{}”.format(int_to_convert)

print(type(int_converted_via_format))

print(int_converted_via_format)

 

<class ‘int’>

10

<class ‘str’>

10

By Using f-string

The last method on our list that you can use to convert integer to string in Python 3 uses f-string. In Python’s source code, f-string is a literal string, with a prefix f, which stores expressions inside {} braces and provides a way to embed these expressions inside strings, using minimal syntax. Note that you can only use f-string Python 3 onward. It’s not available in Python 2. Let us see how:

int_to_convert = 10

 

# checking the type of int_to_convert

print(type(int_to_convert))

print(int_to_convert)

 

# converting int_to_convert to string

int_converted_via_fstring = f'{int_to_convert}’

 

# printing the type of int_converted_via_fstring

print(type(int_converted_via_fstring))

print(int_converted_via_fstring)

 

<class ‘int’>

10

<class ‘str’>

10

Example — Concatenating a String and an Integer

Let us look at an example where we concatenate a String and an Integer by converting the integer into a string using the str() function. We can use this when we want to, say, print a string that also contains information stored in an integer variable.

int_to_concatenate = 7

int_to_concatenate_converted = str(7)

 

# Concatenating the string with the string version of int_to_concatenate

print(“A week has ” + int_to_concatenate_converted + ” days.”)

 

# Returning empty string if no argument is provided

print(str())

Output:

A week has 7 days.

Concatenating Strings and Integers While Avoiding Conversions

Some better, more succinct ways to concatenate strings than just using str() would include using the format function or, even better: f-strings, which is a new addition in Python 3.

Here’s how we can achieve the same goal using these two tools:

Concatenation Using format Function

int_to_concatenate = 7

 

# Concatenates using the format function, without conversion

print(“A week has {x} days.”.format(x=int_to_concatenate))

Output:

A week has 7 days.

Concatenation Using f-strings Function

int_to_concatenate = 7

 

# Concatenates using f-string function, without conversion

print(f”A week has {int_to_concatenate} days.”)

Output:

A week has 7 days.

Interview Questions on Converting Integer to String in Python

Here are a few examples of technical interview questions that will require you to convert an integer into a string:

  1. Write a function that takes in an integer and returns the string representation of that integer without using methods that would make the solution trivial.
  2. Convert String to Int and Int to String in one step.
  3. Convert an integer into a hexadecimal string.
  4. What are the different ways to convert an integer to a string in Python?
  5. How would you concatenate strings and integers while avoiding conversions?

FAQs on Converting Integer to String in Python

Question 1: How can I concatenate multiple integers into part of the same string using the format function?

You can use all of the four methods that we have provided above for this purpose; here’s an example using the format function with multiple placeholders:

Syntax: {}{}{}.format(value_a, value_b, value_c)

Example:

str_one = “String with {} multiple {} placeholders {}! ”

str_formatted = str_one.format(5, 6, 7)

print(str_formatted)

Output:

String with 5 multiple 6 placeholders 7!

Question 2: When would we need to convert int to string?

Converting an integer to a string can be useful in the following cases:

  • To concatenate two or more integers
  • To find out if a digit is present in a large integer
  • To print an integer as a part of a string that describes what the integral value represents

Question 3: What are some cases where we need to do the opposite: convert a string to an integer? How can we convert a string into an integer in Python?

One common case of need to convert a string to an integer is that if the input is an integer read as a string, we need to convert the string to an integer to do numerical operations using the input. This conversion can be achieved using the int() function using the syntax: print(int(“String”))

Ready to Nail Your Next Coding Interview?

Whether you’re a coding engineer gunning for a software developer, software engineer, tech lead, or management position at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation! To learn more, sign up for our FREE webinar.

As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

Last updated on: September 25, 2024
Author
Dipen Dadhaniya
Engineering Manager at Interview Kickstart
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Spring vs Spring Boot

Spring vs Spring Boot: Simplifying Java Application Development

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Product Marketing vs Product Management

Product Marketing vs Product Management

Java Scanner reset()

The upper() Function in Python

Insertion Sort Algorithm

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC