Use isalpha() Function in Python with Example

The `isalpha()` function in Python is a string method used to check whether all the characters in a given string are alphabetic (letters only). It returns `True` if all characters in the string are alphabetic and the string is non-empty, otherwise it returns `False`.

Syntax

string.isalpha()

Example

Here’s an example to demonstrate the usage of the `isalpha()` function:

```python
# Example 1: All alphabetic characters
str1 = "Hello"
print(str1.isalpha()) # Output: True

# Example 2: Contains non-alphabetic characters
str2 = "Hello123"
print(str2.isalpha()) # Output: False

# Example 3: Contains space
str3 = "Hello World"
print(str3.isalpha()) # Output: False

# Example 4: Empty string
str4 = ""
print(str4.isalpha()) # Output: False
```

Explanation

Example 1: The string `”Hello”` contains only alphabetic characters, so `isalpha()` returns `True`.
Example 2: The string `”Hello123″` contains numbers along with alphabetic characters, so `isalpha()` returns `False`.
Example 3: The string `”Hello World”` contains a space, which is not an alphabetic character, so `isalpha()` returns `False`.
Example 4: An empty string is checked, and since it contains no characters, `isalpha()` returns `False`.

The `isalpha()` function is useful when you want to ensure that a string contains only letters before performing further operations on it.