Python 字串 isalnum() 方法



Python 字串isalnum()方法用於檢查字串是否僅由字母數字字元組成。如果輸入字串中的所有字元都是字母數字字元且至少有一個字元,則此方法返回 True;否則返回 False。

如果字元'char'對以下所有函式返回 True,則它被認為是字母數字字元:char.isalpha(),char.isdecimal(),char.isdigit() 或 char.isnumeric()。也就是說,字元必須是小寫字母、大寫字母、數字或十進位制數。除此之外的其他類別不被認為是字母數字字元。

讓我們在下一節中更詳細地瞭解此函式。

語法

以下是 Python 字串isalnum()方法的語法:

str.isalnum()

引數

Python 字串isalnum()方法不包含任何引數。

返回值

如果字串中的所有字元都是字母數字字元且至少有一個字元,則 Python 字串isalnum()方法返回 True;否則返回 False。

示例

小寫字母、大寫字母和數字屬於字母數字字元。

以下是 Python 字串isalnum()方法的一個示例。在這個例子中,我們試圖找出字串“tutorial”是否為字母數字。

str = "tutorial"
result=str.isalnum()
print("Are all the characters of the string alphanumeric?", result)

執行上述程式後,將生成以下輸出:

Are all the characters of the string alphanumeric? True

示例

只有小寫字母、大寫字母和數字屬於字母數字字元。其他字元,例如 '!'、'.'、'/' 等,不是字母數字字元。即使包含字母的字串包含這些非字母數字字元,isalnum()函式也會返回 False。

str = "Hello!Welcome."
result=str.isalnum()
print("Are all the characters of the string alphanumeric?", result)

執行上述程式後,將獲得以下輸出:

Are all the characters of the string alphanumeric? False

示例

只有小寫字母、大寫字母和數字屬於字母數字字元。其他字元,例如 '!'、'.'、'/'、'@'、'#' 等,不是字母數字字元。當isalnum()方法應用於包含這些字元的字串時,它將返回 False。

str = "#@%$"
result=str.isalnum()
print("Are all the characters of the string alphanumeric?", result)

執行上述程式後,將獲得以下輸出:

Are all the characters of the string alphanumeric? False

示例

只有小寫字母、大寫字母和數字屬於字母數字字元。其他字元,例如 '!'、'.'、'/' 等,不是字母數字字元。

str = "Aa12"
result=str.isalnum()
print("Are all the characters of the string alphanumeric?", result)

上述程式執行後,將顯示以下輸出:

Are all the characters of the string alphanumeric? True

示例

小寫字母、大寫字母和數字被視為字母數字字元。甚至空格“ ”也不被視為字母數字字元。

str = "1234567189 "
result=str.isalnum()
print("Are all the characters of the string alphanumeric?", result)

上述程式的輸出如下所示:

Are all the characters of the string alphanumeric? False
python_strings.htm
廣告