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
String to Int and Int to String in Python Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting a string to int and int to string. Converting a string to an int If we want to convert a number that is represented in the string to int, we have
2 min read
How to convert string to integer in Python? In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equiv
3 min read
Convert integer to string in Python In this article, weâll explore different methods for converting an integer to a string in Python. The most straightforward approach is using the str() function.Using str() Functionstr() function is the simplest and most commonly used method to convert an integer to a string.Pythonn = 42 s = str(n) p
2 min read
Convert Object to String in Python Python provides built-in type conversion functions to easily transform one data type into another. This article explores the process of converting objects into strings which is a basic aspect of Python programming.Since every element in Python is an object, we can use the built-in str() and repr() m
2 min read
Convert Hex String To Integer in Python Hexadecimal representation is commonly used in computer science and programming, especially when dealing with low-level operations or data encoding. In Python, converting a hex string to an integer is a frequent operation, and developers have multiple approaches at their disposal to achieve this tas
2 min read
Convert String to Int in Python In Python, converting a string to an integer is important for performing mathematical operations, processing user input and efficiently handling data. This article will explore different ways to perform this conversion, including error handling and other method to validate input string during conver
3 min read