0

I have a string that consist of characters which all of them divided by comma and I want to create a list with the integers only. I wrote:

str = '-4,, 5, 170.5,4,s, k4, 4k, 1.3,  ,, 8'.replace(' ','')
# Now the str without spaces: '-4,,5,170.5,4,s,k4,4k,1.3,,,8'

lst_str = [item for item in str.split(',')
# Now I have a list with the all items: ['-4', '5', '170.5', '4' ,'s', 'k4' ,'4k', '1.3', '8']

int_str = [num for num in lst_str if num.isdigit]
# The problem is with negative character and strings like '4k'
# and 'k4' which I don't want, and my code doesn't work with them.

#I want this: ['-4', '5', '4', '8'] which I can changed after any item to type int.

Can someone help me how to do that? Without importing any class. I didn't find an answer for this specific question (its my first question)

Vincent Doba
  • 4,343
  • 3
  • 22
  • 42
Ys99
  • 1
  • 1
  • following EAFP you can write a function that converts `str` to `int` by calling `int` and treating exceptions like `None`s for example and then filter them out – Azat Ibrakov Apr 28 '21 at 08:41

6 Answers6

2

isdigit() is a function, not property. It should be called with (). It will also won't work on negative numbers, you can remove the minus sign for the check

int_str = [num for num in lst_str if num.replace('-', '').isdigit()]
# output: ['-4', '5', '4', '8']

If you need to avoid a case of '-4-' use number of occurrences parameter

num.replace('-', '', 1)
Guy
  • 46,488
  • 10
  • 44
  • 88
0

Try this:

def check_int(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False
    
int_str = [num for num in lst_str if check_int(num)]
Rishin Rahim
  • 655
  • 4
  • 14
0

I did it using this:

string = '-400,, 5, 170.5,4,s, k4, 4k, 1.3,  ,, 8'.replace(' ','')
# Now the str without spaces: '-4,,5,170.5,4,s,k4,4k,1.3,,,8'

let_str = [item for item in string.split(',')]
# Now I have a list with the all items: ['-4', '5', '170.5', '4' ,'s', 'k4' ,'4k', '1.3', '8']
neg_int = [num for num in let_str if "-" in num]

int_str = [num for num in let_str if num.isdigit()]
neg_int = [num for num in neg_int if num[1:].isdigit()]

for num in neg_int: int_str.append(num)
print(int_str)
python_ged
  • 600
  • 2
  • 10
0

This is very close to the question Python - How to convert only numbers in a mixed list into float? if you combine it with python: extract integers from mixed list.

Your "filter" does not filter at all - the function num.isdigit on a non-null string instance named num is always true.

Instead of floats you use ints: Create a function that tries to parse something to an int, if not return None. Only keep those that are not None.

text  = '-4,, 5, 170.5,4,s, k4, 4k, 1.3,  ,, 8'    
cleaned = [i.strip() for i in text.split(',') if i.strip()]

def tryParseInt(s):
    """Return integer or None depending on input."""
    try:
        return int(s)
    except ValueError:
        return None

# create the integers from strings that are integers, remove all others 
numbers = [tryParseInt(i) for i in cleaned if tryParseInt(i) is not None]

print(cleaned)
print(numbers)

Output:

['-4', '5', '170.5', '4', 's', 'k4', '4k', '1.3', '8']
[-4, 5, 4, 8]
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

How about a regex solution:

import re

str = '-4,, 5, 170.5,4,s, k4, 4k, 1.3,  ,, 8'
int_str = [num for num in re.split(',\s*', str) if re.match(r'^-?\d+$', num)]
tshiono
  • 21,248
  • 2
  • 14
  • 22
0

You can try to replace num.isdigit with this function :

def isNumber(str):
    try:
        int(str)
        return True
    except:
        return False

Example:int_str = [num for num in lst_str if isNumber(num)]

crownZ
  • 73
  • 9