Home > Enterprise >  Remove non numeric characters from a list
Remove non numeric characters from a list

Time:01-09

I have a list that looks like this:

Amount = [USD $35 m, CAD $ 45 Millon, AED 25Mil ]

I am looking for an output:

Amount = [35,45,25]

I appreciate your help!!

CodePudding user response:

You can use a regex to achieve what you want :

import re

amount = ['USD $35 m', 'CAD $ 45 Millon', 'AED 25Mil' ]

print([re.sub(r'[^\d\.]', '', a) for a in amount])

This one takes floating point number in consideration, if not change it with this one :

re.sub(r'[^\d]', '', a)

CodePudding user response:

For:

Amount = ["USD $35 m", "CAD $ 45 Millon", "AED 25Mil"]

You can do this:

print([int("".join([ch for ch in el if ch in "0123456789"])) for el in Amount])

or

print([int("".join([ch for ch in el if ch.isdigit()])) for el in Amount])

Output:

[35, 45, 25]

IMPORTANT: If you have float values please use regex solution! This is NOT working for such element:

"Value 2.5 M€" >> 25

CodePudding user response:

amount = ["$36", "Test", 46, "26€"]
output = []

for x in amount:
    number = ""
    for char in [*str(x)]:
        if char.isnumeric():
            number  = str(char)
    if number != '':
        output.append(int(number))

print(output)

Output will be: [36, 46, 26]

You're welcome :)

CodePudding user response:

assuming that the values in the amount list are strings you can do like this:

amount = ['USD $35 m', 'CAD $ 45 Millon', 'AED 25Mil' ]
result = []
for i in amount:
    num = ''
    for j in i:
        if j.isnumeric():
            num = num   j
    result.append(num)
print(result)  # ['35', '45', '25']

You can also make it a function. Like this:

amount = ['USD $35 m', 'CAD $ 45 Millon', 'AED 25Mil' ]

def get_nums(amount_list):
    result = []
    for i in amount_list:
        num = ''
        for j in i:
            if j.isnumeric():
                num = num   j
        result.append(num)
    return result
    
print(get_nums(amount))  # ['35', '45', '25']

• See this link to more information about isdigit(), isnumeric(), and isdecimal() in python. It maybe be useful to your project.

CodePudding user response:

amount = ['USD $35 m', 'CAD $ 45 Millon', 'AED 25Mil']
output = []
for element in amount:
     curr = ''
     for char in element:
         if char.isdigit():
             curr  = char
     output.append(curr)
output = [int(str_num) for str_num in output]
print(output)
  • Related