Explain Codes LogoExplain Codes Logo

Convert integer to string in Python

python
string-conversion
data-types
exception-handling
Anton ShumikhinbyAnton Shumikhin·Sep 29, 2024
TLDR

To convert an integer to a string in Python, you should use the built-in str() function. Here’s how you do it:

number = 123 str_num = str(number) print(str_num) # '123'

In this example, str() method turns the integer 123 into the string '123'.

Strings, Integers, and why Conversion?

In programming, data types are fundamental as each is designed to manage specific kinds of data.

  • String data constitutes textual content (like sentences, single characters, or symbols).
  • Integer data, on the other hand, represents whole numbers.

So why convert integers to strings? Some common scenarios include:

  • String formatting/interpolation: Your buddy integer becomes one of the cool string kids and can strut its stuff with other strings in a sentence.
  • File I/O: When writing data to a text file, it's best if all residents in the text file speak the same language ― string, that is!
  • Web transfer: In backend development, when numerical data needs to journey over a network, packing it up as a string can make the trip smoother.

Adding Personality: Customizing Conversion

When you've got your custom objects and you want a tailored string conversion method, adding a __str__() method to your class will give you direction over the conversion.

class Product: def __init__(self, name, price): self.name = name self.price = price def __str__(self): return f"Product \"{self.name}\" is cheap! Only 💲{self.price}" p = Product('Cup', 5.99) print(str(p)) # 'Product "Cup" is cheap! Only 💲5.99'

Here, your Product object isn't just an object, it's a cheap product! Printing a string representation demonstrates exactly how you want it presented.

Never Trust User Input: Exception Handling

Always be prepared for user-input surprises. Safeguard your application by handling exceptions and consider trying on a try-except armor.

try: user_input = "1024" number = int(user_input) # Try converting input to an integer except ValueError: number = 0 # Oops! Error? Assign a default value. print("Call the number police! We got a non-numeric input.")

Who needs good users when your code is robust? Remember, user input is like Schrödinger's cat—it could be a number or not a number until observed (or parsed!).

Precision Matters: Float to String Conversion

When dealing with floats, precision is like a fine wine's taste—it matters! F-strings and the format() method can help make the numbers look perfect.

pi = 3.14159 # Three digits should be enough. Any more and we're just showing off. print(f"{pi:.3f}") # '3.142'

The ".3f" format specification in the f-string rounds the float to three decimal places.