-1

Example Input:

'hi6 my name is-34 have you seen96?'

Example Output:

[6, -34, 96]

I have tried:

def extractor(string):
      list1 = [n for n in string if n.isnumber()]
      print(list1)

I want to extract even those integers, which are concatenated with some character too.

HIMANSHU PANDEY
  • 684
  • 1
  • 10
  • 22
Mezza
  • 23
  • 3
  • "I also tried to use a more complex program, with multiple methods, if, range etc. but nothing." We can only tell you what went wrong with those approaches if you show them. Alternately: did you try to use a search engine to look for existing approaches? For example, you could try putting `python find numbers in string` [into a search engine](https://duckduckgo.com/?q=python+find+numbers+in+string), which is how I found the linked duplicate. – Karl Knechtel Oct 22 '21 at 10:04

2 Answers2

0

The most straightforward would be using regular expressions:

import re

def extractor(string):
    return [int(s) for s in re.findall(r"-?\d+", string)]
    # return [*map(int, re.findall(r"-?\d+", string))]

extractor("hi6 my name is-34 have you seen96?")
# [6, -34, 96]

-?: an optional "-"
\d+: one or more digits

Documentation:

user2390182
  • 72,016
  • 6
  • 67
  • 89
0

As suggested by user2390182, you can use Regex(Regular Expressions) for solving this problem.
Adding to it, more straightforward regex will be as follows:

import re
def Extract_Numbers(Str): return re.findall('(-*[0-9]+)', Str)

print(Extract_Numbers("hi6 my name is-34 have you seen96?")) # ['6', '-34', '96']

You can also put the import statement inside the function to make it usable across your projects....

def Extract_Numbers(Str):
    import re
    return re.findall('(-*[0-9]+)', Str)

print(Extract_Numbers("hi6 my name is-34 have you seen96?")) # ['6', '-34', '96']
HIMANSHU PANDEY
  • 684
  • 1
  • 10
  • 22