-1

I have the code:

user_input = input('>>>: ')
if not re.search('[0-9]', user_input):
    print('That wasn\'t an integer.')
else:
    print('That was an integer!')
    print(user_input)

It basically tries to determine if the user's input is (mathematically) an integer or not. This works if the input is 'adgx'; the code recognizes that these aren't within the range 0-9, and print's 'That wasn't an integer.'. I need the program to print 'That wasn't an integer.' if the input is for example 'a3h1d', but it doesn't. I assume because the input technically contained numbers that were within the range, it satisfied the statement. I need it so that if the input is 'a3h1d' that the program prints 'That wasn't an integer.'.

Anya
  • 395
  • 2
  • 13

2 Answers2

1

If you aren't tied to the idea of using a regex for this, I would suggest simply using str.isdigit

user_input = input('>>>: ')
if not user_input.isdigit():
    print('That wasn\'t an integer.')
else:
    print('That was an integer!')

There's also this approach

try:
    user_input = int(input('>>>: '))
    print('That was an integer!')
except ValueError:
    print('That wasn\'t an integer.')
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • I can't use try, because though i know i didn't include it but i have now after editing, because then it will convert '00000000' to '0' when i need to print it – Anya Apr 12 '17 at 16:40
0

You can also use re.match() plus the beginning-of-string and end-of-string markers:

user_input = input('>>>: ')
if not re.match('^[0-9]+$', user_input):
    print('That wasn\'t an integer.')
else:
    print('That was an integer!')

Remember that, in regex:

  • ^ Matches the start of a line;
  • $ Matches the end of a line;
  • + Indicates that the previous pattern should appear one or more times.

I would recommend taking a look at Python official 're' documentation for a more complete and well explained list.

Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80