Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to use .replace and .strip? Python

Tags:

python

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.

like image 510
alienware13user Avatar asked Apr 11 '17 19:04

alienware13user


People also ask

Why is strip () not working Python?

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.

Can you use .replace on a string in Python?

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.

How do you replace all occurrences of a string in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.


1 Answers

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.

like image 165
axwr Avatar answered Sep 26 '22 13:09

axwr