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.
JavaScript
x
2
1
currency_list = ['USD', 'UNITED STATES DOLLAR', '$', 'EUR', 'EURO', '€', 'GBP','BRITISH POUND', '£']
2
Normally input string can be
JavaScript
1
7
1
"$1212212"
2
"1212212EURO"
3
"1212212"
4
"1212212 BRITISH POUND"
5
6
need help to validate values like "1212$343" or "1212212EURO323.23"
7
Code:
JavaScript
1
4
1
for symb in currency_list:
2
if symb in amount:
3
data = amount.replace(symb, '')
4
Advertisement
Answer
You can use regex to achieve your purpose.
JavaScript
1
20
20
1
import re
2
3
currency_list = ['USD', 'UNITED STATES DOLLAR', '$', 'EUR', 'EURO', '€', 'GBP', 'BRITISH POUND', '£']
4
5
p = re.compile(r'([D]*)([d]+.?[d]+)(.*)')
6
7
def verify_or_get_amount(amount):
8
first, mid, last = [i.strip() for i in p.search(amount).groups()]
9
10
if (first and first not in currency_list) or (last and last not in currency_list):
11
print('invalid:', amount)
12
else:
13
amount = mid
14
print('amount:', amount)
15
return mid
16
17
18
for i in ['EURO123', 'EURO 123', 'EURO 123.', 'EURO .12', 'EURO 12.12', '$1212212', '1212212EURO', '1212212', '1212212 BRITISH POUND', '1212$343']:
19
verify_or_get_amount(i)
20