IsString

T

Tuvas

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!
 
R

Rick Wotnaz

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!

If you really need to, you can test for type:
.... print type(x)

<type 'str'>
<type 'int'>
.... if type(x) is str: print "it's a string"
.... elif type(x) is int: print "it's an int"
.... elif type(x) is float: print "it's a float"
.... elif type(x) is complex: print "it's a complex number"

it's a string
it's an int
it's a float
it's a complex number
 
G

Gary Herron

Tuvas said:
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!
In Python, all values have an associated type which you can query with
type(v) thus:

from types import *

if type(v) == IntType:
... whatever ...

Several types would qualify as "numbers": IntType, FloatType, LongType,
and ComplexType,
and several as "strings": StringType and UnicodeType

Gary Herron
 
P

Peter Decker

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!

Use isinstance().

e.g.:

x = 7
isinstance(x, int)
-> True
isinstance(x, basestring)
-> False
x = "Hello"
isinstance(x, int)
-> False
isinstance(x, basestring)
-> True

I always use the basestring class for comparison, unless I need to
know whether or not the string is unicode.
 
L

Larry Bates

Tuvas said:
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!
You can test the type of the object as follows:
The old way was to use type(a), but I think isinstance is
the new "preferred" method.

Larry Bates
 
S

Steven Bethard

Tuvas said:
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...

STeVe
 
S

Steven D'Aprano

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
 
S

Steven Bethard

Steven said:
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

Or better yet, use str.isdigit:

py> '6'.isdigit()
True
py> 'x'.isdigit()
False
py> def is_single_digit(s):
.... return len(s) == 1 and s.isdigit()
....
py> is_single_digit('6')
True
py> is_single_digit('66')
False

STeVe
 
L

Larry Bates

Steven said:
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

I had the same thought, but reread the post. He asks "if a given
variable is a character or a number". I figured that even if he
is coming from another language he knows the difference between
"a given variable" and the "contents of a give variable". I guess
we will see.... ;-). This list is so good, he gets BOTH questions
answered.

-Larry Bates
 
S

Steven D'Aprano

On Mon, 12 Dec 2005 18:51:36 -0600, Larry Bates wrote:

[snippidy-doo-dah]
I had the same thought, but reread the post. He asks "if a given
variable is a character or a number". I figured that even if he
is coming from another language he knows the difference between
"a given variable" and the "contents of a give variable". I guess
we will see.... ;-). This list is so good, he gets BOTH questions
answered.

The problem is, Python doesn't have variables (although it is
oh-so-tempting to use the word, I sometimes do myself). It has names in
namespaces, and objects.

It be a subtle difference, but an important one. That's why, for instance,
Python is neither call by reference nor call by value, it is call by
object.
 
D

Duncan Booth

Gary said:
In Python, all values have an associated type which you can query with
type(v) thus:

from types import *

if type(v) == IntType:
... whatever ...

Several types would qualify as "numbers": IntType, FloatType, LongType,
and ComplexType,
and several as "strings": StringType and UnicodeType

This is bad practice on so many levels...

If you really do need to test for a type use isinstance, not
'type(v)==something'.

You didn't need to import any of those types from types: they are all
builtins albeit under different names.

If you really must:

if isinstance(v, (int, float, long, complex)):
...

or for strings use the base type:

if isinstance(v, basestring):
...
 
T

Tuvas

LOL. As to me being a newbie to programming, well, I've been
programming to some extent for the last 10 years, although never
professionally. The first few questions were enough to help me solve
the problem that I had. And I've been programming Python for 4 months
or so, but it's been pretty intense, my current code is about 1000
lines or so for the program that I am doing. The reason I had this need
is basically trying to correct a mistake that I had made, sometime I
passed a function characters, other times I passed it numbers, and I
needed to have one uniform system. But, after a while, I found that I
really didn't need this uniformed system, so I was alright. But, thanks
for all of our help!
 
T

Tom Anderson

On Mon, 12 Dec 2005 18:51:36 -0600, Larry Bates wrote:

[snippidy-doo-dah]
I had the same thought, but reread the post. He asks "if a given
variable is a character or a number". I figured that even if he is
coming from another language he knows the difference between "a given
variable" and the "contents of a give variable". I guess we will
see.... ;-). This list is so good, he gets BOTH questions answered.

The problem is, Python doesn't have variables (although it is
oh-so-tempting to use the word, I sometimes do myself). It has names in
namespaces, and objects.

In what sense are the names-bound-to-references-to-objects not variables?
It be a subtle difference, but an important one.

No, it's just spin, bizarre spin for which i can see no reason. Python has
variables.
That's why, for instance, Python is neither call by reference nor call
by value, it is call by object.

No, python is call by value, and it happens that all values are pointers.
Just like java, but without the primitive types, and like LISP, and like a
load of other languages. Python's parameter passing is NO DIFFERENT to
that in those languages, and those languages are ALL described as
call-by-value, so to claim that python does not use call-by-reference but
some random new 'call-by-object' convention is incorrect, unneccessary,
confusing and silly.

</rant>

I'm sure this has been argued over many times here, and we still
all have our different ideas, so please just ignore this post!

tom
 
S

Steve Holden

Tom said:
On Mon, 12 Dec 2005 18:51:36 -0600, Larry Bates wrote:

[snippidy-doo-dah]

I had the same thought, but reread the post. He asks "if a given
variable is a character or a number". I figured that even if he is
coming from another language he knows the difference between "a given
variable" and the "contents of a give variable". I guess we will
see.... ;-). This list is so good, he gets BOTH questions answered.

The problem is, Python doesn't have variables (although it is
oh-so-tempting to use the word, I sometimes do myself). It has names in
namespaces, and objects.


In what sense are the names-bound-to-references-to-objects not variables?
In a very important sense, one which you should understand in order to
understand the nature of Python.

In C if you declare a variable as (for example) a character string of
length 24, the compiler will generate code that allocates 24 bytes to
this variable on the stack frame local to the function in which it's
declared. Similarly if you declare a variable as a double-length
floating point number the compiler will emit code that allocates 16
bytes on the local stack-frame.

In Python a name (*not* a "variable", though people do talk loosely
about "instance variables" and "class variables" just to be able to use
terms familiar to users of other to languages) is simply *bound* to a
value. The only storage that is required, therefore, is enough to hold a
pointer (to the value currently bound to the name). Thus assignment
(i.e. binding to a name, as opposed to binding to an element of a data
structure) NEVER copes the object, it simply stores a pointer to the
bound object in the part of the local namespace allocated to that name.
No, it's just spin, bizarre spin for which i can see no reason. Python has
variables.
You appear very confident of your ignorance ;-)
No, python is call by value, and it happens that all values are pointers.
Just like java, but without the primitive types, and like LISP, and like a
load of other languages. Python's parameter passing is NO DIFFERENT to
that in those languages, and those languages are ALL described as
call-by-value, so to claim that python does not use call-by-reference but
some random new 'call-by-object' convention is incorrect, unneccessary,
confusing and silly.

</rant>

I'm sure this has been argued over many times here, and we still
all have our different ideas, so please just ignore this post!
Couldn't!

I do apologise, though, for any implication you assertions are based on
ignorance because you do demonstrate quite a sophisticated knowledge of
what goes on under the hood. As long as you can accept that "Python
'variables' are all references" then the rest is indeed semantics.

Of course it will be helpful for newcomers if we can adopt a standard
terminology ...

regards
Steve
 
F

Fredrik Lundh

Steve said:
In Python a name (*not* a "variable", though people do talk loosely
about "instance variables" and "class variables" just to be able to use
terms familiar to users of other to languages) is simply *bound* to a
value. The only storage that is required, therefore, is enough to hold a
pointer (to the value currently bound to the name).

in tom's world, the value of an object is the pointer to the object, not the
object itself, so I'm not sure he can make sense of your explanation.

</F>
 
X

Xavier Morel

Tom said:
In what sense are the names-bound-to-references-to-objects not variables?

In the sense that a variable has various meta-informations (at least a
type) while a Python name has no information. A Python name would be
equivalent to a C void pointer, it can mean *any*thing and has no
value/meaning by itself, only the object it references has.
 
S

Steven D'Aprano

On Mon, 12 Dec 2005 18:51:36 -0600, Larry Bates wrote:

[snippidy-doo-dah]
I had the same thought, but reread the post. He asks "if a given
variable is a character or a number". I figured that even if he is
coming from another language he knows the difference between "a given
variable" and the "contents of a give variable". I guess we will
see.... ;-). This list is so good, he gets BOTH questions answered.

The problem is, Python doesn't have variables (although it is
oh-so-tempting to use the word, I sometimes do myself). It has names in
namespaces, and objects.

In what sense are the names-bound-to-references-to-objects not variables?

Because saying "Python has variables" leads to nonsense like the following:

[snip]
No, python is call by value, and it happens that all values are
pointers.

All values in Python are pointers???

So when I write:

name = "spam spam spam spam"

the value of the variable "name" is a pointer, and not a string. Riiight.

Call by value and call by reference have established meanings in
computer science, and Python doesn't behave the same as either of them.
Consider the following function:

def modify(L):
"Modify a list and return it."
L.append(None); return L

If I call that function:

mylist = range(10**10) # it is a BIG list
anotherlist = modify(mylist)

if the language is call by value, mylist is DUPLICATED before being
passed to the function. That does not happen in Python. Consequently,
expected behaviour of a call by value language is that anotherlist and
mylist will be different. That is not true in Python either. So Python is
not call by value.

But neither is it call by reference. If it were call by reference, I could
write something like this:


def increment(n):
"""Add one to the argument changing it in place."""
# In Pascal, I would need the var keyword to get this behaviour,
# but Python is call by reference so all variables are passed
# by reference.
n += 1

x = 1
increment(x)
assert x == 2

but that doesn't work in Python either.

So Python behaves demonstrably different from BOTH call by value and call
by reference. Consequently, it is neither of them.

The conceptual problem you are having is that you are conflating the
object model of Python the language with the mechanism of the underlying C
implementation, which does simply pass pointers around. But when
discussing the behaviour of Python, what counts is the behaviour of Python
code, not the underlying C mechanism -- which may be different than the
underlying Java mechanism in JPython, or Python mechanism in PyPython.


[snip]
I'm sure this has been argued over many times here, and we still
all have our different ideas, so please just ignore this post!

I'd love to, but unfortunately I've already hit send on my reply.
 
X

Xavier Morel

Steven said:
name = "spam spam spam spam"

the value of the variable "name" is a pointer, and not a string. Riiight.
Yes, it's a reference to an object of type string holding the value
def increment(n):
"""Add one to the argument changing it in place."""
# In Pascal, I would need the var keyword to get this behaviour,
# but Python is call by reference so all variables are passed
# by reference.
n += 1

x = 1
increment(x)
assert x == 2

but that doesn't work in Python either.

That example is mightily flawed since Python's integers are immutable
objects.

Here, python creates a new integer object of value "n+1" and binds the
_local_ name "n" to this new object. n isn't bound to it's initial
object anymore (the one x is bound to), and therefore can't modify it.

Now use a mutable type instead of an immutable int and you'll notice a
pass-by-reference behavior.
 
S

Steven D'Aprano

Yes, it's a reference to an object of type string holding the value
<spam spam spam spam>

The underlying C implementation might be that, but we're not talking about
the underlying C implementation, where talking about the Python level.
Python does not have pointers. If you want to go down the path of
treating Python as if it were the underlying implementation, I'll just
argue that everything in Python is untyped bytes, because that's the way
the machine code executed by the CPU sees things.

That example is mightily flawed since Python's integers are immutable
objects.

That's the *reason* why the behaviour doesn't work. But the *fact* that it
doesn't work is enough to prove that Python is not call by reference. Call
by reference *demands* the ability to do that sort of thing.
Now use a mutable type instead of an immutable int and you'll notice a
pass-by-reference behavior.

Wrong. Will this example clarify things?

def modify_in_place(obj):
"""Modify an arbitrary object in place."""
obj = None

x = [1, 2, 3] # mutable object
modify_in_place(x)
assert x is None


Doesn't work either.

Sometimes call by object behaves like call by reference, and sometimes
like call by value, but it is not either of them.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top