Python : Correct way to strip <p> and </p> from string?
I want to strip out <p>
and </p>
from a string (lets say s
).
Right now I am doing this :
s.strip('"<p>""</p>"')
I am not really sure if what I am doing is correct, but this has been effective enough with most of the strings that I have used.
Except, I still get the following string : Here goes..</p>
Is there any other effective way to strip? It does not need to fast or efficient. I need something effective that get's the work done.
Test Case
Let's say:
s="<p>Here goes..</p>"
After performing the necessa开发者_开发技巧ry operations on s
, print s
should give :
Here goes..
If you're dealing with a lot of HTML/XML, you might want to use a parser to easily and safely manipulate it instead of using basic string manipulation functions. I really like BeautifulSoup for this kind of work. It works with invalid markup and has a really elegant API.
In your example, you could use it like this:
>>> soup = BeautifulSoup('<p>hello world</p>')
>>> soup.text
u'hello world'
Assuming you're not trying to sanitise XML/HTML the following will work:
s = s.replace('<p>', '').replace('</p>', '')
You are trying to strip the whole all characters present in the "<p>""</p>"
string from your values. strip
treats this value as a set, it'll remove any "
, <
, p
, /
, or >
from your string.
>>> s = 'Here goes "/p>'
>>> s.strip('"<p>""</p>"')
'Here goes '
So, using strip
(and rstrip
and lstrip
) is only suitable if you want to remove sets of characters, not a multi-character string as a whole.
If you want to remove <p>
from the start and </p>
from the end, you could use the following:
if s.startswith('<p>'):
s = s[3:]
if s.endswith('</p>'):
s = s[:-4]
If you need to remove these from elsewhere in the string, you need to use s.replace
:
s.replace('<p>', '').replace('</p>', '')
or you could look into regular expressions.
You could use regex for that, just an import and one line:
>>> import re
>>> s="text<p>text</p>text"
>>> re.sub("</?p>","",s)
'texttexttext'
The reason of split("</p>")
's fail is trying to strip <
,/
,p
or >
; not </p>
.
s="<p>Here goes..</p>"
s = s.lstrip("<p>")
s = s.rstrip("</p>").strip('.')
精彩评论