How to type negative number with .isdigit?

前端 未结 4 1397
无人及你
无人及你 2020-12-09 09:58

when I try this

if question.isdigit() is True:

I can type in numbers fine, and this would filter out alpha/alphanumeric strings

whe

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 10:05

    I have just had a similar question on edabit where I realised that negative numbers returned as False whilst using isnumeric(). I have put my solution below: Create a function that takes a list of strings and integers, and filters out the list so that it returns a list of integers only.

    def filter_list(list):
        numbers = [i for i in list if str(i).isnumeric() == True]
        for i in list:
            try:
                int(i)
                if i <0:
                    numbers.append(i)
            except ValueError:
                continue
        return numbers
    list = [1,2,3,'a','b','c', -6, 0]
    print(filter_list(list))
    

    I am still new to Python so this is a basic attempt. Feel free to let me know if there is a much easier or better looking way.

提交回复
热议问题