Sentry Answers>Python>

How do I parse a string to a float or int?

How do I parse a string to a float or int?

Gareth D.

The Problem

How do I parse a string to a float or int in Python?

For example, I have a string like “1337” or “13.37” and I want to parse it to an int or float data type.

The Solution

If your string input is clean and predictable, the easiest way to parse a string to a float or int is by using the float or int built-in modules.

To cast a string to a float:

Click to Copy
my_float_str = "13.37" my_float_float = float(my_float_str) print(my_float_float) # will print 13.37

To cast a string to an int:

Click to Copy
my_int_str = "1337" my_int_int = int(my_int_str) print(my_int_int) # will print 1337

In some situations, you may need to account for edge cases. For example, you can’t use the int module if your input contains non-numerical characters such as a period.

Click to Copy
my_float_str = "13.37" # do not do this my_int_str = int(my_float_str)

This will result in the following error:

Click to Copy
Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '13.37'

If you are happy to throw away the floating point component (that is, round down to the nearest integer), you can first cast the string to a float and then cast the resulting float to an int. For example:

Click to Copy
my_float_str = "13.37" my_int_str = int(float(my_float_str)) print(my_int_str) # will print 13

Note that float will still throw an error if you try to parse a string with more than one period. For example:

Click to Copy
float("123.456.789") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: could not convert string to float: '123.456.789'

If your input is dirty or unpredictable, you’ll need to implement some additional error handling or add a data cleaning step before attempting to cast your data to different types. For example, you can use a try-except statement to catch a ValueError exception:

Click to Copy
try: not_a_float = float("123.456.789") except ValueError: print("Could not parse string to float")
  • Sentry BlogPython Performance Testing: A Comprehensive Guide
  • Syntax.fmListen to the Syntax Podcast
  • Sentry BlogLogging in Python: A Developer’s Guide
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.