String isalnum() Method in Python

Python String isalnum() Method

The isalnum() method in Python is used to check whether a string contains only alphanumeric characters. It returns True if all the characters in the string are alphanumeric, meaning they are either letters (a-z, A-Z) or digits (0-9). Otherwise, it returns False.

Here's the syntax of the isalnum() method:

string.isalnum()

Example:

# Examples of isalnum() method
string1 = "Hello123"
string2 = "Hello, world!"
string3 = "12345"

result1 = string1.isalnum()
result2 = string2.isalnum()
result3 = string3.isalnum()

print("String 1:", string1)
print("String 2:", string2)
print("String 3:", string3)

print("isalnum() result for String 1:", result1)
print("isalnum() result for String 2:", result2)
print("isalnum() result for String 3:", result3)

Output:

String 1: Hello123
String 2: Hello, world!
String 3: 12345
isalnum() result for String 1: True
isalnum() result for String 2: False
isalnum() result for String 3: True

In this example, string1 contains alphanumeric characters only ("Hello123"), so isalnum() returns True. string2 contains a space and punctuation marks, so it is not composed of only alphanumeric characters, and thus isalnum() returns False. string3 contains only digits ("12345"), so isalnum() returns True.

The isalnum() method can be used to validate user input, check if a string contains only letters and digits, or to perform basic input validation for certain applications.