Python Forum
Detecting float or int in a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Detecting float or int in a string
#11
(May-23-2022, 10:02 PM)Clunk_Head Wrote: I found regex to be slower than replace() by at least a factor of 10
I'm pretty confident that regex will be faster than your recursive function with many ifs. Still, the officially pythonic way is to try to convert and catch an exception...
Reply
#12
(May-23-2022, 09:49 PM)bowlofred Wrote: You're doing recursive function calls. Would need to test, but I'd worry that would have a bigger impact on memory than a try block.

Good point. I will test it and see. I may have to unroll the recursion and test that too.

(May-23-2022, 09:49 PM)bowlofred Wrote: I believe your function will pass the strings ++-+3 and 3e, while float() will not.

Unrolling the recursion should allow me to correct that.
Reply
#13
(May-23-2022, 09:30 PM)Gribouillis Wrote: In some other languages, we would need to declare all the exception types that are thrown by the function, which is tedious. But not in Python.

I think therein lies my issue, having been raised on ASM/C/C++
Reply
#14
(May-23-2022, 08:49 PM)Clunk_Head Wrote: Can you please provide an example where an exception must be used in place of anything else?

Python documentation, glossary:

Quote:EAFP
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

There are many countries out there with different notations. 1.000,42 and 1,000.42 are perfectly 'legal' and equal numbers, just depending your locale.

There is ast.literal_eval() which can be used (locale thingy still applies):

>>> import ast
>>> ast.literal_eval('1.0')
1.0
>>> ast.literal_eval('+3')
3
>>> ast.literal_eval('-42')
-42
>>> type(ast.literal_eval('-42'))
<class 'int'>
If you feed invalid value then you get SyntaxError:

>>> ast.literal_eval('1.0.0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/ast.py", line 62, in literal_eval
    node_or_string = parse(node_or_string.lstrip(" \t"), mode='eval')
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/ast.py", line 50, in parse
    return compile(source, filename, mode, flags,
  File "<unknown>", line 1
    1.0.0
       ^^
SyntaxError: invalid syntax
You can use EAFP style with try to literally evaluate value, catch syntax error if it's raised and do something about it
Clunk_Head and Gribouillis like this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#15
Here's how I settled it to meet pythonic standards as well as those I was raised on.
In this application, a calculator, I was originally doing this:
1) Try to convert to float
2) except, check against operator list
3) if not in list, then it's an invalid expression

But if I swap those checks around:
1) Check against operator list
2) if not in list, try to convert to float
3) except, invalid expression
While minor it satisfies my desire to keep exceptions for exceptions.

Thanks to all who replied, I learned a lot. I will be more open-minded about try/except blocks in python.
Reply
#16
I don't know, but I suspect, behind the scenes, within isnumeric(), re is being used anyway.

Is there another, better way to find numbers?

Why not just use re explicitly? Then you can see exactly what is going on.

import re
things = [1.5, '2.5', 3.5, '4.5', 'a.bc', 'cde. do', 2, 7, '2.A', '2.2.', '2.A2', 1.56, 2.77, '3.33.33']
my_pattern = re.compile("\d+\.\d+")
for t in things:
    match_f = re.search(my_pattern, str(t))
    print(t, match_f)
And with the output of match_f.span() you can slice the number from a string!
Clunk_Head likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python calculate float plus float is incorrect? sirocawa 6 291 Apr-16-2024, 01:45 PM
Last Post: DeaD_EyE
  convert string to float in list jacklee26 6 1,914 Feb-13-2023, 01:14 AM
Last Post: jacklee26
  iterating and detecting the last Skaperen 3 1,082 Oct-01-2022, 05:23 AM
Last Post: Gribouillis
  TypeError: float() argument must be a string or a number, not 'list' Anldra12 2 4,878 Jul-01-2022, 01:23 PM
Last Post: deanhystad
  Convert string to float problem vasik006 8 3,407 Jun-03-2022, 06:41 PM
Last Post: deanhystad
  module detecting if imported vs not Skaperen 1 1,679 Nov-19-2021, 07:43 AM
Last Post: Yoriz
  detecting a generstor passed to a funtion Skaperen 9 3,616 Sep-23-2021, 01:29 AM
Last Post: Skaperen
  Python BLE Scanner not detecting device alexanderDennisEnviro500 0 2,011 Aug-01-2021, 02:29 AM
Last Post: alexanderDennisEnviro500
  Detecting power plug Narayan 2 2,720 Aug-01-2020, 04:29 AM
Last Post: bowlofred
  ValueError: could not convert string to float: RandomCoder 3 5,769 Jul-27-2020, 07:38 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020