1

This is a very basic question ..sorry....I'm a newbie. A few specifications: -The string is an arithmetic expression. -It would love the output to return the number i.e a 2 digit number or 3 digit number depending on the string. For example if string is "12+3-5/6" Then the output should be 12. I have tried this:

import re
s = "12*9-6/4"
m = re.search("\d" , s)
if m:
    print(s[m.start()])
else:
    print("try again")

But this outputs the first number it sees and not the whole 2 digit number. How do I change it?

input = '123abc456def'
output = re.findall(r'^\d+', input)

But this returns the value in square brackets. Ht do I just get a number.

Shesps
  • 41
  • 6
  • Or: https://stackoverflow.com/questions/32571348/getting-only-the-first-number-from-string-in-python – BERA May 31 '18 at 11:17
  • You should split the string based on the operations ('*', '+', '-') and you can have an array of all the numbers. – Alexandru Pupsa May 31 '18 at 11:18

2 Answers2

3

Without regex, you can use next with a generator comprehension and enumerate:

s = '12*9-6/4'

idx = next((i for i, j in enumerate(s) if not j.isdigit()), len(s))

res = int(s[:idx])  # 12

Explanation

  • The generator comprehension iterates over an enumerated s, yielding (0, '1'), (1, '2'), (2, '*'), etc.
  • With next, we find the first instance j.isdigit evaluates to true for a character in s.
  • We then extract the index i; if no such character exists, we use the length of the string.
  • Finally, we use s[:idx] to slice the string up to but not including the calculated index.
jpp
  • 159,742
  • 34
  • 281
  • 339
0

Try using re.match

Ex:

import re
s = "12*9-6/4"
m = re.match("(?P<first>\d+)" , s)
if m:
    print(m.group('first'))
else:
    print("try again")

Output:

12
Rakesh
  • 81,458
  • 17
  • 76
  • 113