IsString

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Dec 12 23:35:24 CET 2005


On Mon, 12 Dec 2005 14:24:48 -0700, Steven Bethard wrote:

> Tuvas wrote:
>> I need a function that will tell if a given variable is a character or
>> a number. Is there a way to do this? Thanks!
> 
> What's your use case?  This need is incommon in Python...

No offense to the four or five helpful folks who answered Tuvas with
explanations of type() and isinstance(), but there is such a thing as dumb
insolence. I should know, I've done it often enough: answer the question
the person asks, instead of the question you know he means.

Satisfying, isn't it? *wink*

Judging by the tone of the original poster's question, I'd say for sure he
is an utter Python newbie, probably a newbie in programming in general,
so I bet that what (s)he really wants is something like this:

somefunction("6")
-> It is a number.

somefunction("x")
-> It is a character.


So, at the risk of completely underestimating Tuvas' level of programming
sophistication, I'm going to answer the question I think he meant to ask:
how do I tell the difference between a digit and a non-digit?

import string
def isDigit(s):
    if len(s) != 1:
        # a digit must be a single character, anything more
        # or less can't be a digit
        return False
    else:
        return s in string.digits


If you know that you are only dealing with a single character c, never a
longer string, you can just use the test:

c in string.digits


-- 
Steven.




More information about the Python-list mailing list