简体   繁体   English

如何将字符串(带换行符)转换为 HTML?

[英]How can I convert String (with linebreaks) to HTML?

When I print the string (in Python) coming from a website I scraped it from, it looks like this:当我打印来自我从中抓取的网站的字符串(在 Python 中)时,它看起来像这样:

"His this 

is 

a sample

String"

It does not show the \n breaks.它不显示\n中断。 this is what I see in a Python interpreter.这就是我在 Python 解释器中看到的。

And I want to convert it to HTML that will add in the line breaks.我想将它转换为 HTML ,它将添加换行符。 I was looking around and didn't see any libraries that do this out of the box.我环顾四周,没有看到任何开箱即用的库。

I was thinking BeautifulSoup, but wasn't quite sure.我在想 BeautifulSoup,但不太确定。

如果您有从文件中读取的字符串,则可以通过执行以下操作将\\n替换为<br> ,这是html中的换行符:

my_string.replace('\n', '<br>')

I believe this will work 我相信这会起作用

for line in text:
   for char in line:
      if char == "/n":
         text.replace(char, "<br>")

You can use the python replace(...) method to replace all line breaks with the html version <br> and possibly surround the string in a paragraph tag <p>...</p> . 您可以使用python replace(...)方法将所有换行符替换为html版本<br>并且可以将字符串括在段落标签<p>...</p> Let's say the name of the variable with the text is text : 假设带有文本的变量的名称为text

html = "<p>" + text.replace("\n", "<br>") + "</p>"

searching for this answer in found this, witch is likely better because it encodes all characters, at least for python 3 Python – Convert HTML Characters To Strings在发现这个中搜索这个答案,女巫可能更好,因为它编码所有字符,至少对于 python 3 Python – 将 HTML 字符转换为字符串

# import html
import html

# Create Text
text = 'Γeeks for Γeeks'

# It Converts given text To String
print(html.unescape(text))

# It Converts given text to HTML Entities
print(html.escape(text))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM