首页 > 解决方案 > “你”如何将整个标题保存为字符串?

问题描述

在 Python 中,如果您假设必须将上述字符串保存到变量中,您将如何保存?

编辑:我假设的情况是,如果您有一个函数,可以将网站/PDF 的内容复制到一个变量(例如使用 Pyperclip),然后对该变量执行某些操作。有一个单引号、双引号、三个单引号和三个双引号将立即导致迄今为止提出的每个解决方案中的错误。

标签: pythonstring

解决方案


如果您尝试将其键入为字符串,它将不起作用。但是,如果您将数据行拉入变量中,Python 将自动反斜杠chars它需要。

如果您尝试使用open()and从文件中提取此行,这一点很明显,如果您使用 解析文件readlines(),您将得到相同的结果。HTMLBeautifulSoup

文件包含:

How ' would " you ''' save """ this whole title as a string?

打开和readlines()

with open('data.txt', 'r') as file:
    test = list(file.readlines())

print(test)

输出:

['How \' would " you \'\'\' save """ this whole title as a string?']

HTML文件:

<doctype='HTML'>
How ' would " you ''' save """ this whole title as a string?
</>

来自HTML

from bs4 import BeautifulSoup

soup = BeautifulSoup(open('data.html'), "html.parser")

text = soup.get_text()

print(type(text), text.strip())

输出:

<class 'str'> How ' would " you ''' save """ this whole title as a string?

当您将其附加到列表时,它会返回包含字符转义的字符串。

test.append(text.strip())

print(test)

输出:

['How \' would " you \'\'\' save """ this whole title as a string?']

推荐阅读