Извлечение ненужных символов из строки "[(-1,)]", чтобы получилось "-1"

Всем привет! У меня есть строка "[(-1,)]", мне нужно удалить лишние символы, чтобы получилось "-1". Много способов перепробовал, но получилось только с удалением ВСЕХ символов. Надеюсь на вашу помощь!

amount = "[(-1,)]"
amount2 = "".join(c for c in amount if c.isdecimal())
print(amount2)

Output: 1


Ответы (3 шт):

Автор решения: Violet
in:

import re

a = '[(-1,)]'

print(f'type a: {a}, {type(a)}')
print(f'a replace: {a.replace("[(", "").replace(",", "").replace(")]", "")}')
print(f'a strip: {a.strip("[(,)]")}')
print('a regexp:', re.findall(r'\W\d', a)[0])

b = [(-1,)]

print(f'type b: {b}, {type(b)}')
print(f'type b[0]: {b[0]}, {type(b[0])}')
print(f'b join + loop: {"".join([str(x[0]) for x in b])}')

out:

type a: [(-1,)], <class 'str'>
a replace: -1
a strip: -1
a regexp: -1

type b: [(-1,)], <class 'list'>
type b[0]: (-1,), <class 'tuple'>
b join + loop: -1
→ Ссылка
Автор решения: Mikhail Murugov

ast.literal_eval

import ast

amount = "[(-1,)]"
result = ast.literal_eval(amount)[0][0]
→ Ссылка
Автор решения: Qwertiy

https://ideone.com/ZHbwRw

import re

s = "[(-1,)]"
res = re.search(r"-?\d+", s)
if res != None: res = int(res.group(0))
print(res)
→ Ссылка