some_bloody_fool
some_bloody_fool

Reputation: 4685

How to use Python to ensure a string is only numbers and then convert it to an integer

If i have a string like this: asdf5493

I need the last four digits and i get it by doing this:

strVar[-4:]

Is it possible to then see if they are all numbers?

Upvotes: 3

Views: 172

Answers (2)

mac
mac

Reputation: 43031

EDIT: This was written before Sven's own edit to his answer. Similar in essence but this version with cope with the . as well.


Are you trying to check if the last four characters are all digits or if the last four characters form a number?

If it is the first case, Sven's answer is what you are looking for. If it is the latter, here's way you can do the check:

def test_last_four(string):
    try:
        float(string[-4:])
        return True
    except ValueError:
        return False

HTH!

Upvotes: 4

Sven Marnach
Sven Marnach

Reputation: 601559

strVar[-4:].isdigit()

tests if all four characters are digits. Documentation

EDIT: If your actual goal is to convert this number to an integer, the usual idiom in Python is to just try to do this, and catch the exception in case it fails:

s = strVar[-4:]
try:
    i = int(s)
except ValueError:
    # handle the case that it isn't all digits

Upvotes: 8

Related Questions