- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check if a string has at least one letter and one number in Python?
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).
import re print(bool(re.match('^(?=.*[0-9]$)(?=.*[a-zA-Z])', 'hasAlphanum123'))) print(bool(re.match('^(?=.*[0-9])(?=.*[a-zA-Z]$)', 'some string')))
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.
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')
This gives us the output −
- Program to check whether every one has at least a friend or not in Python
- Check if both halves of the string have at least one different character in Python
- Python program to check if two lists have at least one common element
- Program to check if binary string has at most one segment of ones or not using Python
- C# program to check if two lists have at-least one element common
- How to aggregate two lists if at least one element matches in MongoDB?
- Check if a string has all characters with same frequency with one variation allowed in Python
- Program to check every sublist in a list containing at least one unique element in Python
- Check if a binary string has two consecutive occurrences of one everywhere in C++
- Check if each internal node of a BST has exactly one child in Python
- Count number of paths whose weight is exactly X and has at-least one edge of weight M in C++
- Java regex program to verify whether a String contains at least one alphanumeric character.
- How to subset R data frame rows if at least one or more values matches?
- How to remove rows that contain at least one 0 in R?
- How to extract columns having at least one non-duplicate in R?