Reputation: 9323
I'm working through a Python 3 book and came across the string function isidentifier(). The text description is "s.isidentifier() : Returns True if s is non empty and is a valid identifier". I tested it in the Python Shell like this:
>>> s = 'test'
>>> s.isidentifier()
True
>>> 'blah'.isidentifier()
True
I would expect the 2nd statement to return false since 'blah' is not held in a variable. Can anyone explain this? Thanks.
Upvotes: 3
Views: 7406
Reputation: 69
isidentifier
is a Python function that simply tests whether a string contains only certain characters (underscore, digits, and alphas) and starts with an alpha or an underscore, so the string can be used for a valid Python identifier. Other functions that test for character classes are isalpha
, isalnum
, isdigit
, and others.
ss = (
'varABC123',
'123ABCvar',
'_123ABCvar',
'var_ABC_123',
'var-ABC-123',
'var.ABC.123',
# check your own strings
)
fmt = '%-15s%-10s%-10s%-10s%-10s'
print(fmt % ('', 'isalpha', 'isalnum', 'isdigit', 'isidentifier'))
for s in ss:
print(fmt % (s, s.isalpha(), s.isalnum(), s.isdigit(), s.isidentifier()))
Result:
isalpha isalnum isdigit isidentifier
varABC123 False True False True
123ABCvar False True False False
_123ABCvar False False False True
var_ABC_123 False False False True
var-ABC-123 False False False False
var.ABC.123 False False False False
Upvotes: 4
Reputation: 96211
Python doesn't have "variables". It is more helpful to think in terms of objects.
'blah'
definitely exists at the time 'blah'.isidentifier()
is called (after all it means that "call isidentifier()
method of the string object 'blah'
").
So if your understanding were correct, isidentifier()
method of string objects should always return True
, because at the time of the call, the object definitely exists.
What isidentifier()
does is to check that the string object can be used as a valid identifier. Try these two lines in your Python session for example:
>>> a = "$"
>>> "$".isidentifier()
Even though "$"
is assigned to the name a
, the isidentifier()
call returns False
since $
is not a valid identifier in Python.
Upvotes: 5
Reputation: 102745
Returns True if s is non empty and is a valid identifier.
What they mean is that s could be valid as an identifier. It doesn't imply that it is an identifier that's in use.
Your first example is showing the same thing: 'test' (what isidentifier
is actually checking) is not the name of a variable either. I think you meant
>>> 's'.isidentifier()
True
Upvotes: 12
Reputation: 4857
"isidentifier" doesn't say anything about the "variable" the string being tested is referenced by. So
'blah'.isidentifier()
is identical to
s = 'blah'
s.isidentifier()
In Python, it's never (or rarely) about the "variable" (Python doesn't have variables), it's about the object. In this case, strings.
Upvotes: 5