Python 字串 isidentifier() 方法



Python 字串isidentifier() 方法用於檢查一個字串是否為有效的識別符號。識別符號是在 Python 程式碼中用於標識變數函式、類、模組或其他物件的名稱。

如果字串滿足以下條件,則被認為是有效的識別符號:

  • 以字母 (a-z, A-Z) 或下劃線 "_" 開頭。
  • 字串中其餘字元為字母、數字 (0-9) 或下劃線 _。

語法

以下是 Python 字串isidentifier() 方法的基本語法:

string.isidentifier()

引數

此方法不接受任何引數。

返回值

該方法返回布林值“True”或“False”。如果字串根據Python 語法規則是有效的識別符號,則返回“True”,否則返回“False”。

示例 1

在以下示例中,我們使用isidentifier() 方法檢查字串“my_variable”是否為有效的 Python 識別符號:

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

輸出

獲得的輸出如下:

The result is: True

示例 2

在這裡,我們使用isidentifier() 方法檢查字串“class”是否為有效的 Python 識別符號:

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

輸出

儘管“class”是一個保留關鍵字,但它仍然是一個有效的識別符號,因此isidentifier() 方法返回 True,如下面的輸出所示:

The result is: True

示例 3

在以下示例中,我們使用 isidentifier() 方法檢查“下劃線”是否為有效的識別符號:

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

輸出

產生的結果如下所示:

The result is: True

示例 4

在這裡,我們檢查字串“123variable”是否為有效的 Python 識別符號,它不是,因為識別符號不能以數字開頭。因此,isidentifier() 方法返回 False:

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

輸出

我們得到如下所示的輸出:

The result is: False
python_string_methods.htm
廣告