I want to input a string into a function and get the integer that's in it to compare the number with another expression. I've searched a lot but some don't work or give me this: ['6']. I can't compare that to a number so it can't work. Please Help.

{def numberC(card):
#numbers = []
#numbers.append(re.findall(\-?\d+, card))
#nums = re.compile(r"[+-]?\d+(?:\.\d+)?")
print(re.findall("\-?\d+", card))
return re.findall("\-?\d+", card)}

That is the function I've made that doesn't work.

The string that goes into it looks like this "Red Card 10".

I then use this to compare them as a card battle.

{elif(card1 == card2):
    if(numberC(card1) < numberC(card2)):
        return "Player 2 is the Winner!"
    else:
        return "Player 1 is the Winner!"}

The expected result is from "Red Card 10" I want just 10 that has a data type of an integer.

2 Answers

0
Rakesh On

Use re.search

Ex:

def numberC(card):
    return re.search("\-?(\d+)", card).group(1)
0
Community On

You need to treat special cards cases, for the Ace, Jack, Queen, King and Joker (maybe). Feel free to change their values:

import re

SPECIAL_CARDS = {
  "ace": 1,
  "jack": 11,
  "queen": 12,
  "king": 13,
  "joker": 20
}

def numberC(card):
  card = card.lower()
  special = set(SPECIAL_CARDS) & set(card.split())
  if special:
    return SPECIAL_CARDS[special.pop()]
  result = re.search("\d+", card)
  if not result:
    return 0
  return int(result.group())

print(numberC("Red Card 10"))
print(numberC("10 Red Card"))
print(numberC("Ace Red Card"))
print(numberC("Black Jack Card"))
print(numberC("I am not a card"))

Returns:

10
10
1
11
0