Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python String isidentifier() Method



The Python Stringisidentifier() method is used to check whether astring is a valid identifier. An identifier is a name used to identifyvariables,functions, classes,modules, or other objects in Python code.

A string is considered a valid identifier if −

  • It starts with a letter (a-z, A-Z) or an underscore "_".
  • The remaining characters in the string are letters, digits (0-9), or underscores _.

Syntax

Following is the basic syntax of the Python Stringisidentifier() method −

string.isidentifier()

Parameters

This method does not accept any parameter.

Return Value

The method returns a boolean value "True" or "False". It returns "True" if the string is a valid identifier according toPython syntax rules, otherwise it returns "False".

Example 1

In the following example, we are checking whether the string "my_variable" is a valid Python identifier using theisidentifier() method −

identifier = "my_variable"result = identifier.isidentifier()print("The result is:",result)

Output

The output obtained is as follows −

The result is: True

Example 2

Here, we use theisidentifier() method to check whether the string "class" is a valid Python identifier −

identifier = "class"result = identifier.isidentifier()print("The result is:",result)

Output

Despite being a reserved keyword, "class" is still a valid identifier, so theisidentifier() method returns True as shown in the output below −

The result is: True

Example 3

In the following example, we check whether the "underscores" are valid identifiers using the isidentifier() method −

identifier = "_"result = identifier.isidentifier()print("The result is:",result)

Output

The result produced is as shown below −

The result is: True

Example 4

In here, we check whether the string "123variable" is a valid Python identifier, which it isn't because identifiers cannot start with a digit. Therefore, theisidentifier() method returns False −

identifier = "123variable"result = identifier.isidentifier()print("The result is:",result)

Output

We get the output as shown below −

The result is: False
python_string_methods.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp