5

Hi Id like to know if I can tidy up my code any better than I have.

Basically the answer would be something likex = "£1,094.99 " Im using x.strip() and x.strip("£") and x.replace(",") and then x = float(x) * 1.18 to convert figure into euros.

Any way to make this more efficient? Im a newbie so i just wondered.

0

4 Answers 4

9

a nice one liner i use quite often is this:

x = ''.join([c for c in x if c in '1234567890.'])

So something like this:

x = "$1,094.99"
x = ''.join([c for c in x if c in '1234567890.'])
print x

will give you an output of:

1094.99

Then you can use your float(x) * 1.18 as you have been. I find this to be a good method as it is some what robust. stray characters and dollar signs instead of pound signs shouldn't stop it from working.

3
  • @alienware13user Its basically looking at all of the characters in the string x (c for c in x) and if that character is in the string '1234567890.' then it returns that character. otherwise it skips it.
    – axwr
    Apr 11, 2017 at 19:56
  • Ah thanks -I know Im not meant to comment thanks. but thanks :P Apr 11, 2017 at 20:00
  • @alienware13user no worries, i think it was a good question as you've got three different answers all of which are right for different scenarios. Whelp, one of them dissappeared. Still an interesting question though.
    – axwr
    Apr 11, 2017 at 20:01
5

you can replace it to ''

float(data.replace(',','').replace('£',''))*1.18
1
  • This answer is nice as well, i think it is better than mine if you want to make sure only the pound and commas are replaced but worse if you want to strip any currency symbol. Also i imagine some people would find the replace syntax easier to read than the "x for x in..."
    – axwr
    Apr 11, 2017 at 19:52
1

Although it's not using .split, but i always find for problem where you want to grab all non-delimiter strings (numbers in this case), it's worth using regex. You just need to find non-white or '.'

import re
x = "£1,094.99 "
number = float(''.join(re.findall('\w+|\.',s)))
euro = number * 1.18
0

You can do this elegantly using re and decimal module, like this :

# -*- coding: utf-8 -*-
from re import sub
from decimal import Decimal
x = "£1,094.99" 
value = Decimal(sub(r'[^\d.]', '', x))
print(value)
value_euro = float(value) * 1.18
print(value_euro)

This will result in :

1094.99
1292.0882
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.