简体   繁体   中英

Remove non numeric characters from a list

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!!

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)

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
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:)

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM