Convert Strings to Numbers and Numbers to Strings in Python
Last Updated :
06 Jan, 2025
Converting strings to numbers and numbers to strings is a common task in Python. In this article, we’ll explore simple ways to convert between strings and numbers .
Using int() and str()
int()
and str()
functions in Python are commonly used for converting data types. The int()
function changes a string or number into an integer, while the str()
function converts a number or object into a string, making it easy to work with different data formats.
Python
# Convert `s1` to integer
s1 = "123"
res = int(s1)
print(type(res))
# Convert `a` to string
a = 123
res= str(a)
print(type(res))
Output<class 'int'>
<class 'str'>
Let's understand different method to convert string to number and number to string.
Using eval()
eval()
function evaluates a string as a Python expression and returns the result. While it can be used to convert strings to numbers, such as integers or floats .
Python
# Convert `s1` to Integer
s1 = "123"
res = int(s1)
print(type(res))
# Convert `s2` to Float
s2 = "123.45"
res = float(s2)
print(type(res))
Output<class 'int'>
<class 'float'>
Using ast.literal_eval()
ast.literal_eval()
function safely evaluates a string containing a Python literal or container display, such as strings, numbers, tuples, lists, dicts, sets, booleans, and None
.
Python
import ast
# String to Integer
s1 = "123"
res = ast.literal_eval(s1)
print(type(res))
# String to Float
s2 = "123.45"
res = ast.literal_eval(s2)
print(type(res))
Output<class 'int'>
<class 'float'>
Explanation:
- ast.literal_eval(s1):This takes the string "123" and treats it as a Python number. Since "123" is a valid integer, it returns the integer 123.
- ast.literal_eval(s2):This takes the string "123.45" and treats it as a valid float, safely returning the value 123.45.
format()
is a efficient way to format strings, especially when we need to include numbers within the string or apply specific formatting like decimal precision or comma separators.
Python
# Convert int to String
a = 123
res = "{}".format(a)
print(type(res))
# Convert float to String
b = 123.45
res = "{:.2f}".format(b)
print(type(res))
Output<class 'str'>
<class 'str'>
Explanation:
"{}".format(a)
: This is used to format and insert the value of a
(123) into the string placeholder {}
. This converts the integer to its string representation, "123"
."
{:.2f}"
: This ensures that the float is displayed with exactly two decimal places, even if the original value has more or fewer decimal places.
Using f-strings
F-strings is easy way to turn numbers (like integers and floats) into strings in Python. We can easily format numbers, such as displaying a specific number of decimal places or embedding numbers directly in the text.
Python
# Integer to String
a = 123
res = f"{a}"
print(type(res))
# Float to String
b = 123.45
res = f"{b:.2f}"
print(type(res))
Output<class 'str'>
<class 'str'>
Explanation:
f"{a}"
: This simply converts the integer to a string.f"{b:.2f}":
This
converts the float to a string, ensuring it always has 2 decimal places, even if the number has fewer.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read