In Python, what is the simplest way to convert a number enclosed in parentheses (string) to a negative integer (or float)?
For example, \'(4,301)\' to -4301, as commonly
For Python 3.6, and also handles '-' as 0, and strips excess empty spaces:
def clean_num(num_string):
bad_chars = '(),-'
translator = str.maketrans('', '', bad_chars)
clean_digits = num_string.translate(translator).strip()
if clean_digits == '':
return 0
elif '(' in num_string:
return -float(clean_digits)
else:
return float(clean_digits)