Which, not only is ugly and slow
I’d dispute both.
A regex or other string parsing method would be uglier and slower.
I’m not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn’t introduce much overhead because the most common exception is caught without an extensive search of stack frames.
The issue is that any numeric conversion function has two kinds of results
- A number, if the number is valid
- A status code (e.g., via errno) or exception to show that no valid number could be parsed.
C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.
I think your code for doing this is perfect.
Related Posts:
- How do I parse a string to a float or int?
- can’t multiply sequence by non-int of type ‘float’
- How do you round UP a number?
- How do you round UP a number?
- (Python) TypeError: ‘float’ object is not subscriptable
- Round a floating-point number down to the nearest integer?
- Limiting floats to two decimal points
- TypeError: ‘float’ object not iterable
- How to get a random number between a float range?
- How can I convert a character to a integer in Python, and viceversa?
- Convert columns to string in Pandas
- Change column type in pandas
- Convert bytes to int?
- Python, print all floats to 2 decimal places in output
- How to truncate float values?
- C convert floating point to int
- Python3 Error: TypeError: Can’t convert ‘bytes’ object to str implicitly
- Easy pretty printing of floats?
- Pandas error “Can only use .str accessor with string values”
- Python: Converting string into decimal number
- Convert a Unicode string to a string in Python (containing extra symbols)python string unicode type-conversion
- Float must be a string or a number?
- Checking if a string can be converted to float in Python
- Convert floats to ints in Pandas?
- Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
- Import Error: No module named numpy
- bash: pip: command not found
- Function for Factorial in Python
- TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python3
- Writing a pandas DataFrame to CSV file
- Error: ‘int’ object is not subscriptable – Python
- Purpose of “%matplotlib inline”
- How do I update Anaconda?
- TypeError: ‘str’ object is not callable (Python)
- Dijkstra’s algorithm in python
- DataFrame constructor not properly called! error
- OSError: [WinError 193] %1 is not a valid Win32 application
- How to download a file over HTTP?
- Can’t fix “zipimport.ZipImportError: can’t decompress data; zlib not available” when I type in “python3.6 get-pip.py”
- Arrays used as indices must be of integer (or boolean) type
- Are static class variables possible in Python?
- Why am I getting “LinAlgError: Singular matrix” from grangercausalitytests?
- ‘method’ object is not subscriptable. Don’t know what’s wrong
- Get total of Pandas column
- How do you read from stdin?
- Union of two lists in Python
- Type error: cannot convert the series to
- Reading a binary file with python
- How to determine a Python variable’s type?
- Could not find a version that satisfies the requirement
- Removing Conda environment
- unittest Vs pytest
- Add single element to array in numpy
- ‘Can’t set attribute’ with new-style properties in Python
- How to check if a string is a substring of items in a list of strings?
- How to index into a dictionary?
- Add a new item to a dictionary in Python
- reducing number of plot ticks
- How can I add new keys to a dictionary?
- Convert pandas data frame to series
- Decorators with parameters?
- Difference between scikit-learn and sklearn
- How can I create a text input box with Pygame?
- How can I print variable and string on same line in Python?
- SettingWithCopyWarning even when using .loc[row_indexer,col_indexer] = value
- Append a tuple to a list – what’s the difference between two ways?
- No module named Image
- How to fix “TypeError: len() of unsized object”
- ValueError: Unknown projection ‘3d’ (once again)
- Substitution Cipher Python
- Good ways to “expand” a numpy ndarray?
- Python data structure sort list alphabetically
- TypeError: ‘numpy.float64’ object does not support item assignment
- TypeError: unsupported format string passed to list.__format__
- Getting “socket.error: [Errno 61] Connection refused” python paramiko
- python setup.py uninstall
- Why am I getting this unexpected keyword argument TypeError?
- Create numpy matrix filled with NaNs
- python pandas remove duplicate columns
- What is the difference between __str__ and __repr__?
- How often does python flush to a file?
- How to open every file in a folder
- Python iteration over non-sequence
- How do I convert a string to a double in Python?
- _csv.Error: field larger than field limit (131072)
- How do I rotate an image around its center using Pygame?
- How to completely uninstall python 2.7.13 on Ubuntu 16.04
- Calculate weighted average using a pandas/dataframe
- Telling Python to save a .txt file to a certain directory on Windows and Mac
- Spell Checker for Python
- TypeError: coercing to Unicode: need string or buffer, int found
- Simplify Chained Comparison
- How to get POSTed JSON in Flask?
- How to fix SSL issue SSL_CTX_use_certificate : ca md too weak on Python Zeep
- Paramiko’s SSHClient with SFTP
- Package libffi was not found in the pkg-config search path REDHAT6.5
- Line is too long. Django PEP8
- TypeError: zip argument #2 must support iteration
- CS231n: How to calculate gradient for Softmax loss function?
- How to create a new database using SQLAlchemy?