Removing an element from a string
I have a specific problem concerning strings. I have a string which has a dollar sign and sometimes a comma. Basically I am scraping a number with selenium and it can come in two forms:
-
$257,873
(with comma) -
$257
(without comma)
How can I remove the comma only if there is one?
This is what I tried:
mc1 = (mc_txt.text).replace("$", "")
str = ""
for i in range(len(mc1)):
if mc1[i] != ",":
str = str + mc1[i]
mc = int(str)
print(mc)
The statment (mc_txt.text).replace("$", "")
returns a string without any dollar signs. You can use the same trick to remove commas. In fact, since you are only trying to remove the leftmost dollar sign, a better option might be
mc = int(mc_txt.text.lstrip('$').replace(',', ''))
Here are a couple or examples using the REPL:
>>> '$123'.lstrip('$').replace(',', '')
'123'
>>> '$123,000'.lstrip('$').replace(',', '')
'123000'
>>> '123,000'.lstrip('$').replace(',', '')
'123000'
>>> '123'.lstrip('$').replace(',', '')
'123'