-2
import re
s = "  afd [asd] 12  [a34] [ -43 ]tt [+12]xxx"
nums = [int(s) for s in re.findall(r'[^\w]\d+', s)]
print(nums)

----

import re
def integers_in_brackets(s):
  
nums = [int(s) for s in re.findall(r'[^\w]\d+', s)]
print(nums)
    

def main():
     
    print(integers_in_brackets("  afd [asd] [12 ] [a34]  [ -43 ]tt [+12]xxx"))

if __name__ == "__main__":
    main()

Why this causes "ValueError: invalid literal for int() with base 10: '[12'" when I divide it to 2 functions?

khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

0

Your regex matches characters before the number as well - i.e. [^\w] will match non-digit characters.

You should capture just the numeric component - using parentheses.

Try this:

nums = [int(s) for s in re.findall(r'[^\w](\d+)', s)]
costaparas
  • 5,047
  • 11
  • 16
  • 26
  • thank you, this almost works! I need also negative values. what should i add so -43 doesnt change to 43? – keijo123 Dec 07 '20 at 13:04
  • Make the `-` [optional](https://stackoverflow.com/questions/15814592/how-do-i-include-negative-decimal-numbers-in-this-regular-expression). – costaparas Dec 07 '20 at 13:18
0

Why this causes "ValueError: invalid literal for int() with base 10: '[12'" when I divide it to 2 functions?

Because you didn't just refactor your code into two functions the input is different.

At first, your input was " afd [asd] 12 [a34] [ -43 ]tt [+12]xxx"

Next, your input is " afd [asd] [12 ] [a34] [ -43 ]tt [+12]xxx"

Your second input has square brackets and a space wrapping the first "12". If this change in input is intentional, then it is a matter of fixing your regex (but I can't do so because I can't tell the intent of the regex or possible inputs).

13steinj
  • 418
  • 5
  • 12