Skip to content

A new string method, .isnumber() #133318

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
rxzzakcodes opened this issue May 2, 2025 · 3 comments
Closed

A new string method, .isnumber() #133318

rxzzakcodes opened this issue May 2, 2025 · 3 comments
Labels
type-feature A feature request or enhancement

Comments

@rxzzakcodes
Copy link

rxzzakcodes commented May 2, 2025

Feature or enhancement

Proposal:

A string method called .isnumber(), it will check if a string is a float or an integer and return True or False.

def isnumber(text)
    try:
        float(text)
        return True
    except ValueError:
        return False

Examples:

abc = "123"
pi = "3.14159"
hello = "hello"

print(isnumber(abc)) # True
print(isnumber(pi)) # True
print(isnumber(hello)) # False

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

@rxzzakcodes rxzzakcodes added the type-feature A feature request or enhancement label May 2, 2025
@rxzzakcodes
Copy link
Author

if it was a built in string method, instead of using isnumber(variable), you would do variable.isnumber()

@JelleZijlstra
Copy link
Member

str.isnumeric() already exists.

@JelleZijlstra JelleZijlstra closed this as not planned Won't fix, can't repro, duplicate, stale May 2, 2025
@terryjreedy
Copy link
Member

s.isnumeric only works for ints (all digits). For floats, there is usually no need to wrap float()

if fs.isnumber(): <do x>
else: <do y>

is a slower version of

try:
    float(fs)
    <do x>
except ValueError:
    <do y>

In nearly all cases where we want to know if a string can be converted, we want the converted float, and throwing it away just to call float again is poor practice. In Python, try-except is as legitimate as if-else.

Note: New builtin functions are not 'minor features' and always need major discussion and a high bar for adoption. We are also pretty stringent about new methods for built-in classes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-feature A feature request or enhancement
Projects
None yet
Development

No branches or pull requests

3 participants