Check if String starts with a Letter in Python

In this article, we will discuss different ways to check if a string starts with an alphabet or not in Python.

Table Of Contents

Check if String starts with a Letter using Regex

The regex module of Python provides a function regex.search(pattern, string). It accepts a regex pattern and a string as arguments. Then it scans through the string and look for a match to the given regex pattern. If a match is found, then it returns a Match object, otherwise, it returns None.

We will use this function and check if a string starts with an alphabet (either uppercase or lowercase). For this, we will use the regex pattern “^[a-zA-Z]”. This pattern checks that the string must only start with an uppercase or lowercase alphabet. For example,

Example 1:

import re

sample_str = "sample string"

# Check if string starts with a letter
if re.search("^[a-zA-Z]", sample_str) is not None:
    print("The String starts with a letter")
else:
    print("The String do not starts with a letter")

Output:

The String starts with a letter

The given string started with an alphabet.

Example 2:

import re

sample_str = "55 Words"

# Check if string starts with a letter
if re.search("^[a-zA-Z]", sample_str) is not None:
    print("The String starts with a letter")
else:
    print("The String do not starts with a letter")

Output:

The String do not starts with a letter

It was a negative test because the given string started with a number instead of a letter.

Check if String starts with a Letter using isapha()

In Python, the string class provides a function isalpha(). It returns True if all the characters in the string are alphabetic and at least one character in the string. We can use this to check if a string starts with a letter.

Select the first character of string using the subscript operator like str[0] and then call the isalpha() on it to check if the first character is an alphabet or not. Let’s see some examples,

Example 1:

sample_str = "sample string"

# Check if string starts with a letter
if sample_str[0].isalpha():
    print("The String starts with a letter")
else:
    print("The String do not starts with a letter")

Output:

The String starts with a letter

The given string started with an alphabet.

Example 2:

sample_str = "55 Words"

# Check if string starts with a letter
if sample_str[0].isalpha():
    print("The String starts with a letter")
else:
    print("The String do not starts with a letter")

Output:

The String do not starts with a letter

It was a negative test because the given string started with a number instead of a letter.

Summary:

We learned different ways to check if a string starts with an alphabet in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top