dante
dante

Reputation: 73

A way to check if string includes both string and digit at the same time

I'm trying to find the word that includes strings and numbers both at the same time. I tried to do something like:

string = "bear666 got sentenced 70 years in prison"

values = string.split()

for i in values:
    if i.isalpha() and i.isdigit():
        print(i)

but nothing worked. Help would be much appreciated

I'm trying to get beaar666 as an output.

Upvotes: 1

Views: 405

Answers (4)

Mike Robinson
Mike Robinson

Reputation: 8945

Simply use re.search() twice. The first pattern searches for letters; the second searches for digits. if both patterns match, the string contains both letters and digits.

Upvotes: 0

luigigi
luigigi

Reputation: 4215

Try:

import re
string = "bear666 got sentenced 70 years in prison 666dog"
re.findall(r'(?:\d+[a-zA-Z]+|[a-zA-Z]+\d+)', string)

Output:

['bear666', '666dog']

Upvotes: 4

wotanii
wotanii

Reputation: 2826

isalpha() and isdigit() check wether the entire word is only made from digits (or only from letters respectively).

you check both by iterating over all letters of a word, like this:

string = "bear666 got sentenced 70 years in prison"

values = string.split()

for i in values:
    if any(char.isalpha() for char in i) and any(char.isdigit() for char in i):
        print(i)

Upvotes: 2

AmirHmZ
AmirHmZ

Reputation: 556

Try this :

string = "bear666 got sentenced 70 years in prison"
words = string.split(" ")

def hasNumbersAndAlphabets(inputString):
    return any(char.isdigit() for char in inputString) and any(c.isalpha() for c in inputString)

for word in words :
    if hasNumbersAndAlphabets(word) :
        print(word)

Upvotes: 2

Related Questions