Check if a String starts with a Number or Letter in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
6 min

banner

# Table of Contents

  1. Check if a string starts with a Number in Python
  2. Check if a string starts with a Letter in Python

# Check if a string starts with a Number in Python

To check if a string starts with a number:

  1. Access the first character in the string.
  2. Use the str.isdigit() method to check if the character is a number.
  3. The str.isdigit() method will return True if the string starts with a number.
main.py
my_str = '248bobby' if my_str and my_str[0].isdigit(): # ๐Ÿ‘‡๏ธ this runs print('The string starts with a number') else: print('The string does NOT start with a number') print('248bobby'[0].isdigit()) # ๐Ÿ‘‰๏ธ True print('bobby'[0].isdigit()) # ๐Ÿ‘‰๏ธ False print('_bobby'[0].isdigit()) # ๐Ÿ‘‰๏ธ False

check if string starts with number

The code for this article is available on GitHub

If you need to check if a string starts with a letter, click on the following subheading:

We first make sure that the string is not empty before accessing the character at index 0.

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

The str.isdigit() method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

main.py
print('123'.isdigit()) # ๐Ÿ‘‰๏ธ True print('1.23'.isdigit()) # ๐Ÿ‘‰๏ธ False (contains period) print('-123'.isdigit()) # ๐Ÿ‘‰๏ธ False (contains minus)

If the character at index 0 is a digit, then the string starts with a number.

# Handling a scenario where the string is empty

If you try to access the character at index 0 of an empty string, you'd get an error.

You can either use the boolean and operator as we did in the first example or use string slicing to avoid the error.
main.py
my_str = '' if my_str[:1].isdigit(): print('The string starts with a number') else: # ๐Ÿ‘‡๏ธ this runs print('The string does NOT start with a number')

handling scenario where the string is empty

The code for this article is available on GitHub

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

The slice selects the first character in the string if it exists, otherwise an empty string is returned.

# Check if each String in a List starts with a Number

If you need to check if each string in a list starts with a number, use a for loop.

main.py
list_of_strings = ['12ab', '34cd', '56ef'] for item in list_of_strings: if str(item)[:1].isdigit(): print(f'{item} starts with a number') else: print(f'{item} does NOT start with a number') # Output: # 12ab starts with a number # 34cd starts with a number # 56ef starts with a number

check if each string in list starts with number

The code for this article is available on GitHub

# Check if all Strings in a List start with a Number

If you need to check if all strings in a list start with a number, use the all() function.

main.py
list_of_strings = ['12ab', '34cd', '56ef'] if all(str(item)[:1].isdigit() for item in list_of_strings): # ๐Ÿ‘‡๏ธ this runs print('All strings start with a number') else: print('NOT all strings start with a number')

The all() function will only return True if the condition is met for all strings in the list.

# Check if a string starts with a Number using re.match()

Alternatively, you can use the re.match() method.

The re.match() method will return a match object if the string starts with a number, otherwise, None is returned.

main.py
import re def starts_with_number(string): return bool(re.match(r'\d', string)) my_str = '249bobbyhadz' if starts_with_number(my_str): # ๐Ÿ‘‡๏ธ this runs print('The string starts with a number') else: print('The string does NOT start with a number') print(starts_with_number('249bobby')) # ๐Ÿ‘‰๏ธ True print(starts_with_number('__bobby')) # ๐Ÿ‘‰๏ธ False print(starts_with_number('')) # ๐Ÿ‘‰๏ธ False

check if string starts with number using re match

The code for this article is available on GitHub

The re.match() method returns a match object if the provided regular expression is matched in the string.

The match() method returns None if the string doesn't match the regex pattern.

We used the bool() class to convert the match object or None value to a boolean.

The first argument we passed to the re.match() method is a regular expression.

main.py
import re def starts_with_number(string): return bool(re.match(r'\d', string))

The \d character matches the digits [0-9] (and many other digit characters).

The re.match() method only checks if the characters at the beginning of the string match the regular expression, so it does exactly what we need.

If you ever need help reading or writing a regular expression, consult the regular expression syntax subheading in the official docs.

The page contains a list of all of the special characters with many useful examples.

# Check if a string starts with a Number using str.startswith()

You can also use the str.startswith() method to check if a string starts with a specific number.

main.py
my_str = '123bobbyhadz.com' if my_str.startswith('123'): print('The string starts with the number') else: print('The string does NOT start with the number')

check if string starts with number using str startswith

The code for this article is available on GitHub

The str.startswith() method returns True if the string starts with the provided prefix, otherwise the method returns False.

If the string starts with the number 123, then True is returned, otherwise, False is returned.

main.py
my_str = '123bobbyhadz.com' print(my_str.startswith('123')) # ๐Ÿ‘‰๏ธ True print(my_str.startswith('456')) # ๐Ÿ‘‰๏ธ False

# Check if a string starts with a Letter in Python

To check if a string starts with a letter:

  1. Access the first character in the string.
  2. Use the str.isalpha() method to check if the character is a letter.
  3. The str.isalpha() method will return True if the string starts with a letter.
main.py
my_str = 'bobby hadz' if my_str and my_str[0].isalpha(): # ๐Ÿ‘‡๏ธ this runs print('The string starts with a letter') else: print('The string does NOT start with a letter') print('bobby'[0].isalpha()) # ๐Ÿ‘‰๏ธ True print('_bobby'[0].isalpha()) # ๐Ÿ‘‰๏ธ False

We first make sure that the string is not empty before accessing the character at index 0.

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.

The str.isalpha() method returns True if all characters in the string are alphabetic and there is at least one character, otherwise False is returned.

main.py
print('BOBBY'.isalpha()) # ๐Ÿ‘‰๏ธ True print('_BOBBY'.isalpha()) # ๐Ÿ‘‰๏ธ False

The str.isalpha method considers alphabetic characters the ones that are defined in the Unicode character database as "Letter".

# Check if a string starts with an ASCII letter

This is a three-step process:

  1. Use the string.ascii_letters attribute to get a string containing the ASCII letters.
  2. Access the first character in the original string.
  3. Use the in operator to check if the string starts with an ASCII letter.
main.py
import string my_str = 'bobby hadz' ascii_letters = string.ascii_letters # ๐Ÿ‘‡๏ธ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ print(ascii_letters) if my_str and my_str[0] in ascii_letters: # ๐Ÿ‘‡๏ธ this runs print('The string starts with an ASCII letter') else: print('The string does NOT start with an ASCII letter') print('bobby'[0] in ascii_letters) # ๐Ÿ‘‰๏ธ True print('ั„ั„ั„ bobby'[0] in ascii_letters) # ๐Ÿ‘‰๏ธ False
The code for this article is available on GitHub

The string.ascii_letters attribute returns a string containing the lowercase and uppercase ASCII letters.

The in operator tests for membership. For example, x in s evaluates to True if x is a member of s, otherwise it evaluates to False.

# Check if a string starts with a Letter using re.match()

Alternatively, you can use the re.match() method.

The re.match() method will return a match object if the string starts with a letter, otherwise None is returned.

main.py
import re def starts_with_letter(string): return bool(re.match(r'[a-zA-Z]', string)) if starts_with_letter('bhadz'): print('The string starts with a letter') else: print('The string does NOT start with a letter') print(starts_with_letter('bhadz')) # ๐Ÿ‘‰๏ธ True print(starts_with_letter('__bhadz')) # ๐Ÿ‘‰๏ธ False print(starts_with_letter('444bhadz')) # ๐Ÿ‘‰๏ธ False print(starts_with_letter('ะคะค bhadz')) # ๐Ÿ‘‰๏ธ False

The re.match method returns a match object if the provided regular expression is matched in the string.

The match() method returns None if the string doesn't match the regex pattern.

We used the bool() class to convert the match object or None value to a boolean.

The first argument we passed to the re.match() method is a regular expression.

main.py
import re def starts_with_letter(string): return bool(re.match(r'[a-zA-Z]', string))
The code for this article is available on GitHub

The square brackets [] are used to indicate a set of characters.

The a-z and A-Z characters represent lowercase and uppercase ranges of letters.

The re.match() method only checks if the characters at the beginning of the string match the regular expression, so it does exactly what we need.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev