1

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.

dante
  • 73
  • 6
  • 2
    Does this answer your question? [Check if a string contains a number](https://stackoverflow.com/questions/19859282/check-if-a-string-contains-a-number) – DoRemy95 Jan 15 '20 at 15:14
  • 1
    A guy below just wrote almost same thing, thank you for the help as well. – dante Jan 15 '20 at 15:19

4 Answers4

4

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']
luigigi
  • 4,146
  • 1
  • 13
  • 30
2

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)
AmirHmZ
  • 516
  • 3
  • 22
  • 1
    You can do it in one comparison like this: `any(char.isdigit() and char.isalpha() for char in inputString)` that way it's faster. – marcos Jan 15 '20 at 15:19
  • 1
    @Marcos You can't. How can a character be both digit and alphabet at the same time? – Gagan T K Jan 15 '20 at 15:24
  • Oh, my bad, that's `True`, I read what the op wrote. It can't be! @GaganTK – marcos Jan 15 '20 at 15:33
2

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)
wotanii
  • 2,470
  • 20
  • 38
0

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.

Mike Robinson
  • 8,490
  • 5
  • 28
  • 41
  • Well, I'm new to python and don't know how the functions from libraries work so currently I prefer to write codes without them, – dante Jan 15 '20 at 15:41