如果它有“和'?Python,我该怎么读这个字符串

时间:2014-02-22 19:51:46

标签: python html string quote

我有这个字符串基本上是一些html

<acronym class="non-experimental-qualifier" title="Indicates that the information given is not based on experimental findings." onclick="dialog('non_experimental_qualifiers'); Event.stop(event || window.event); return false" onmousedown="Event.stop(event || window.event);">By similarity</acronym>. <a class="attribution" href="http://hamap.expasy.org/unirule/

无论如何我可以在python中将其读作字符串。 。 。通常它只有一种类型的'或'所以我可以用另一种来串起它但......它有两种

我怎么能把它变成一个字符串?像:

html = '<acronym class="non-experimental-qualifier" title="Indicates that the information given is not based on experimental findings." onclick="dialog('non_experimental_qualifiers'); Event.stop(event || window.event); return false" onmousedown="Event.stop(event || window.event);">By similarity</acronym>. <a class="attribution" href="http://hamap.expasy.org/unirule/'

3 个答案:

答案 0 :(得分:2)

您可以使用triple-quoted string

html = '''<acronym class="non-experimental-qualifier" title="Indicates that the information given is not based on experimental findings." onclick="dialog('non_experimental_qualifiers'); Event.stop(event || window.event); return false" onmousedown="Event.stop(event || window.event);">By similarity</acronym>. <a class="attribution" href="http://hamap.expasy.org/unirule/'''

以下是演示:

>>> mystr = '''It's a "string"'''
>>> mystr
'It\'s a "string"'
>>>

答案 1 :(得分:2)

您可以使用\'\"转义引号,也可以使用三引号:

example1 = 'She\'s fond of saying "Hello"'
example2 = "She's fond of saying \"Hello\""
example3 = '''She's fond of saying "Hello"'''
example4 = """She's fond of saying "Hello\""""

请注意三重引号字符串末尾的结束";它必须被逃脱,不计入最后3个收盘价。

演示:

>>> example1 = 'She\'s fond of saying "Hello"'
>>> example2 = "She's fond of saying \"Hello\""
>>> example3 = '''She's fond of saying "Hello"'''
>>> example4 = """She's fond of saying "Hello\""""
>>> example1 == example2 == example3 == example4
True

此外,新行允许并保存在三引号字符串中,从而形成一个非常易读的文字HTML值:

html = '''\
<acronym class="non-experimental-qualifier" 
         title="Indicates that the information given is not based on experimental findings." 
         onclick="dialog('non_experimental_qualifiers'); Event.stop(event || window.event); return false" 
         onmousedown="Event.stop(event || window.event);">By similarity</acronym>. 
    <a class="attribution" href="http://hamap.expasy.org/unirule/'
'''

答案 2 :(得分:1)

我很困惑 - 从外部对象读取字符串,您不需要做任何事情。 Python包含电池并将处理引号。我拿了你的字符串并将其保存在一个文件中,然后使用open()。read()

读取它
>>>mystring = open('c:\\mytest.txt').read()

>>>mystring
'<acronym class="non-experimental-qualifier" title="Indicates that the information given is not based on experimental findings." onclick="dialog(\'non_experimental_qualifiers\'); Event.stop(event || window.event); return false" onmousedown="Event.stop(event || window.event);">By similarity</acronym>. <a class="attribution" href="http://hamap.expasy.org/unirule/'

所以我的问题是,你的意思是读或你是否正在尝试构建一个像上面那样的字符串?