w3resource

Converting strings to numbers in Python

Demonstrate how a string can be converted into an int or float data type

In Python, we can convert a string containing a numerical value to an actual number using the built-in functions int() and float(). Using these functions, you can parse strings and return integers or floating-point numbers.

How to convert a string into an integer (int) or a floating-point number (float):

Example: Converting to int:

Code:

# String containing a numerical value
x_str = "256"
# Convert the string to an integer
num_int = int(x_str)
print(num_int, type(num_int))

Output:

256 <class 'int'>

Example: Converting to float

Code:

# String containing a numerical value
f_str = "22.7"
# Convert the string to a floating-point number
f_float = float(f_str)
print(f_float, type(f_float))

Output:

22.7 <class 'float'>

Strings must represent valid numerical representations when converted to numerical values. ValueErrors will be raised if the string contains non-numeric characters or is not a properly formatted number. For example:

Code:

num_str = "Good, Morning!"
try:
    num_int = int(num_str)
except ValueError as e:
    print(f"Error: {e}")

Output:

Error: invalid literal for int() with base 10: 'Good, Morning!'


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-interview/how-do-you-convert-a-string-containing-a-numeric-value-to-an-actual-number.php