Home > Enterprise >  How Can I Look Through A String in Python?
How Can I Look Through A String in Python?

Time:11-23

I am trying to look through a very long string in Python and I am looking for the value that is in

<p class="price">$VALUE USD</p>

I am currently doing

look = "<p class=\"price\">";
print(site.text.find(look));

Because the will always be there but I am looking for the value of the rest of the line. The value is always changing too so it needs to be flexible. At the end I hope to be able to save something like

<p class="price">$2345.22</p>

to a string.

CodePudding user response:

import re

text = "<p class=\"price\">$2345.22</p>"
regex = re.compile("<p class=\"price\">\\$([.\\d]*)</p>")
print(regex.match(text).group(1)) # -> 2345.22

CodePudding user response:

You can use BeautifulSoup to easily get the text from within the tags. https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text

Another way to get the value will be to use the python split method consecutively

string = '<p >$VALUE USD</p>'
new_string = string.split(">")[1].split("<")[0]
  • Related