Python string Method - isidentifier()

‮igi.www‬ftidea.com

The isidentifier() method is a built-in Python string method that returns a boolean value indicating whether the string is a valid identifier in Python.

In Python, an identifier is a name given to a variable, function, class, module or any other user-defined object. An identifier must follow certain rules and conventions, such as starting with a letter or underscore, and only containing letters, digits, and underscores.

Here's an example that demonstrates the usage of the isidentifier() method:

string1 = "hello_world"
string2 = "123world"
string3 = "if"

print(string1.isidentifier())  # Output: True
print(string2.isidentifier())  # Output: False
print(string3.isidentifier())  # Output: True

In this example, we create three strings: string1 which is a valid identifier, string2 which is not a valid identifier because it starts with a digit, and string3 which is a Python keyword and a valid identifier. We then call the isidentifier() method on each string. The method returns True for string1 and string3 since they are valid identifiers, and False for string2 since it is not a valid identifier.

The isidentifier() method returns True if the string is a valid identifier in Python, and False otherwise. To be a valid identifier, a string must:

  • Start with a letter (a-z or A-Z) or an underscore (_).
  • Only contain letters, digits, and underscores.
  • Not be a Python keyword.

Here are some additional examples:

print("hello".isidentifier())  # Output: True
print("Hello".isidentifier())  # Output: True
print("_hello".isidentifier())  # Output: True
print("123".isidentifier())  # Output: False
print("hello-world".isidentifier())  # Output: False
print("if".isidentifier())  # Output: True
print("def".isidentifier())  # Output: False