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.
strip will not do what you want. strip removes trailing and leading whitespace. This is simply a matter of string immutability and using string1. replace(' ', '') to solve this problem.
You can even replace a whole string of text with a new line of text that you specify. The . replace() method returns a copy of a string. This means that the old substring remains the same, but a new copy gets created – with all of the old text having been replaced by the new text.
The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With