I have this one string, which is actually price, this price value comes with any currency symbol (currency_list), I am trying to remove these currency symbols from price and return only price.
Till now I am able to do it for prefix and suffix currency symbol using below code , everything works till here.
I just want to add one validation where if the symbol is not prefix or suffix like “200$434” in btw, then it should return not valid format. which I am not able to understand how should be implemented.
currency_list = ['USD', 'UNITED STATES DOLLAR', '$', 'EUR', 'EURO', '€', 'GBP','BRITISH POUND', '£']
Normally input string can be
"$1212212" "1212212EURO" "1212212" "1212212 BRITISH POUND" need help to validate values like "1212$343" or "1212212EURO323.23"
Code:
for symb in currency_list: if symb in amount: data = amount.replace(symb, '')
Advertisement
Answer
You can use regex to achieve your purpose.
import re currency_list = ['USD', 'UNITED STATES DOLLAR', '$', 'EUR', 'EURO', '€', 'GBP', 'BRITISH POUND', '£'] p = re.compile(r'([D]*)([d]+.?[d]+)(.*)') def verify_or_get_amount(amount): first, mid, last = [i.strip() for i in p.search(amount).groups()] if (first and first not in currency_list) or (last and last not in currency_list): print('invalid:', amount) else: amount = mid print('amount:', amount) return mid for i in ['EURO123', 'EURO 123', 'EURO 123.', 'EURO .12', 'EURO 12.12', '$1212212', '1212212EURO', '1212212', '1212212 BRITISH POUND', '1212$343']: verify_or_get_amount(i)