删除“\n"从一个字符串,但留下实际的换行符? [英] Remove "\n" from a string, but leave the actual linebreaks?

查看:28
本文介绍了删除“\n"从一个字符串,但留下实际的换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Python 课程,目前的作业是从数据库中获取信息,将其添加到文本框,然后根据文本框内的内容创建 HTML 文件.

I'm doing a Python course, and the current assignment is to take information from a database, add it to a textbox, and then create an HTML file from the content inside the textbox.

一切正常,行中的中断与我将它们输入数据库的方式完全相同.唯一的问题是{{"和}}"在从数据库中检索到文本后被添加到文本周围.所以我把文本变成一个字符串,然后用 [3:-4] 切掉这些东西.但是,由于它现在是一个字符串,因此当它输入到文本框中时,它现在会在文本中逐字写入\n".

Everything works perfectly, with breaks in the lines exactly how I typed them into the database. The only problem is that "{{" and "}}" get added around the text after it's retrieved from the database. So I turn the text into a string and slice that stuff off with [3:-4]. But then, since it's now a string, it now literally writes "\n" into the text when it's inputted into the textbox.

无论如何要切掉括号,不包括\n"文本,但仍然保留换行符?

Is there anyway to slice off the brackets, NOT include the "\n" text, but still keep the linebreaks?

这是在我将文本框转换为字符串和切片之前显示的内容:

Here's what the textbox displays before I turn it into a string and slice:

{{这是我的文字!它看起来很干净,因为它有换行符.甜!}}

{{This is my text! It looks very clean because it has linebreaks. Sweet!}}

然后我把它做成一个字符串并剪掉末端:

And after I make it a string and cut the ends off:

这是我的文字!\n\n括号不见了,但现在你可以看到换行代码了.\n\n蹩脚!

This is my text!\n\nThe brackets are gone but now you can see linebreak code.\n\nLame!

我可以两全其美吗?这是我的代码:

Can I have the best of both worlds? Here's my code:

    # Grabs info from database on button click
def getContent(self):
    c.execute("SELECT HTML FROM Content WHERE conName ='{}'".format(self.contentBox.get()))
    fetch = (c.fetchall())
    return str(fetch)[3:-4]

    # Inserts content into textbox
def setContent(self):
    self.clear()
    combo = self.getContent()
    self.text_body.insert(END,combo)

推荐答案

这意味着您的实际字符串中有 2 个\".格式化后的实际字符串是:这是我的文字!\\n\\n括号不见了,但现在您可以看到换行代码.\\n\\n跛脚!额外的 \ 意味着 \n 实际上应该被打印出来,而不是被称为换行符.

That means that your actual string has 2 '\' in it. Your actual string after formatting it is: this is my text!\\n\\nThe brackets are gone but now you can see linebreak code.\\n\\nLame! the extra \ means that the \n should actually be printed and not referred to as a line break.

这篇关于删除“\n"从一个字符串,但留下实际的换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆