Search code examples
pythonstring-literals

python - str containing whitespace characters and int(str)


I'm trying to write a really simple function. It should return True if given object is a digit (0-9), False otherwise. Here are examples of input and desired output:

is_digit("") => False
is_digit("7") => True
is_digit(" ") => False
is_digit("a") => False
is_digit("a5") => False

My code works for the above examples.

def is_digit(n):
    try: 
        return int(n) in range(0, 10)
    except:
        return False

Trouble is, the function returns True for n = "1\n" when it should return False. So, a string like "1" should be converted to integer and is a digit, but a string like "1\n" should not, yet I don't know how to get around that. How can I account for string literals?

P.S. If my title is lame, advice on renaming it is welcome.


Solution

  • You don't need to define a custom function for this. There is a built-in function for this, namely isdigit().

    You can use it as: "a5".isdigit() or "1/n".isdigit().In both cases it will return False.