# How to check if a string has at least one letter and one number in Python?

PythonServer Side ProgrammingProgramming

The easiest way to check this in python is to use regular expressions. In order to check if the given string has atleast one letter and one number, we use re.match(regex, string).

## example

import re
print(bool(re.match('^(?=.*[0-9]$)(?=.*[a-zA-Z])', 'hasAlphanum123'))) print(bool(re.match('^(?=.*[0-9])(?=.*[a-zA-Z]$)', 'some string')))

## Output

True
False

The ?= syntax is used to call lookaheads in regular expressions. Lookaheads actually look ahead in the string from the current position to find matches in the given string. You can read more about them <a href="http://www.rexegg.com/regex-lookarounds.html" target="_blank">here</a>.

We can also check for one letter and one number using a simple for loop and 2 flags.

## example

def validateString(s):
letter_flag = False
number_flag = False
for i in s:
if i.isalpha():
letter_flag = True
if i.isdigit():
number_flag = True
return letter_flag and number_flag
print validateString('hasAlphanum23')
print validateString('some string')

## Output

This gives us the output −

True
False
Updated on 13-Feb-2020 07:41:24