1

So, I know how to convert basic strings into integers, but how does one convert a string of subtraction (or any other mathematical function)? This doesn't work:

str_a = '10-5'
b = 3
c = int(str_a) + b
ValueError: invalid literal for int() with base 10: '10-5'

So how can I make it to work? c must be equal to 8.

Alexei Dom
  • 137
  • 1
  • 1
  • 11

4 Answers4

2

You can use ast.literal_eval() to evaluate str_a as the following:

import ast

str_a = '10-5'
c = ast.literal_eval(str_a) + 3
print(c)
str_a = '10+5-2' # you can use any operation not just subtraction and you can add as many numbers as you want
c = ast.literal_eval(str_a) + 2
print(c)

Output:

8
15
Mohd
  • 5,523
  • 7
  • 19
  • 30
0

You can use regex:

import re

str_a = '10-5'
vals = map(int, re.split("\W+", str_a))
new_value = vals[0] - vals[-1] + 3

Output:

8
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

Use the builtin str.split.

str_a = '10-5'
left, right = str_a.split('-')
b = 3
c = (int(left) - int(right)) + b

Or use the ast module:

import ast
str_a = '10-5'
b = 3
c = ast.literal_eval(str_a) + b
Zach Gates
  • 4,045
  • 1
  • 27
  • 51
0

Get them with a simple regular expression and then sum them up:

import re

str_a = '10-5'
rx = re.compile(r'[+-]?\d+')

a = sum([int(match.group(0)) for match in rx.finditer(str_a)])

b = 3
c = b + a
print(c)
# 8

Note that there are no security measurements yet (i.e. a float number won't work) - you'll need to precise your requirements here.

Jan
  • 42,290
  • 8
  • 54
  • 79