Kapil G
Kapil G

Reputation: 17

How can I remove character elements from a list?

I am trying to convert a line from a text file into a list. The contents of the test file are:

1 2 3 4 f g

I have read the contents into a list lst = ['1','2','3','4','f','g']. I want to remove 'f' and 'g' (or whatever characters they may be) and convert all the remaining elements to int type. How can I achieve this?

Upvotes: 0

Views: 66

Answers (4)

Shivam Roy
Shivam Roy

Reputation: 2061

You can use the built-in Python method isalpha(). The method returns “True” if all characters in the string are alphabets, Otherwise, it returns “False”. I'm assuming that there are no alpha-numeric elements in your list, and your list contains either digits or alphabets. You could try something like this:

elements = [1, 2, 3, 4, 'f', 'g']
for element in elements:
    if element.isalpha():
       elements.remove(element) #Removing the alphabets
#Converting the remaining elements to int
elements = [ int(x) for x in elements ]
       

Upvotes: 1

WickedPython
WickedPython

Reputation: 64

This is a good time for a list comprehension. Convert to int only if isnumeric()

arr = [int(x) for x in arr if x.isnumeric()]

Upvotes: 2

Instead of removing, rather build a new list. Python is more efficient when just appending items to a list. Here we try to convert i to an int - if it is convertable then it reads as some base-10 number, with possible + or - sign. If it does not match, then int(i) throws a ValueError exception which we just ignore. Those values that were correctly converted will be appended to a new result list.

result = []
for i in elements:
    try:
        result.append(int(i))
    except ValueError:
        pass

Upvotes: 2

Stick-Figure
Stick-Figure

Reputation: 95

Try checking if each character can be converted into a character:

arr = ['1', '2', '3', '4', 'f', 'g']
for c, char in enuemrate(arr[:]):
    try: 
      arr[c] = int(char)
    except ValueError:
      del arr[c]
print(arr)

Upvotes: 1

Related Questions