Remove "\n" from a string, but leave the actual linebreaks? Remove "\n" from a string, but leave the actual linebreaks? tkinter tkinter

Remove "\n" from a string, but leave the actual linebreaks?


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.


The root of the problem is that you are getting data from the database back as a list of lists (though the inner list may be a single element containing the HTML) You start to cause problems when you either insert that data literally into a widget, or if you use str to convert that data to a string.

The reason you see curly braces, for example, is that the the text widget doesn't know how to display a list of lists, so it uses curly braces to delineate list items (there's a good reason, but it's a long explanation). Those curly braces aren't in the actual data from the database, they get added when you try to add a list to the text widget.

The proper solution is to take your database data in it's raw form (list of lists or list of HTML elements) and convert it to a string intelligently. You will then no longer need to trim braces or convert newlines, or do any other sort of hack to make your data look right.

For example, if you want a newline between each row of data, and a space between each column of data (assuming you're getting back more than one column), you can insert the data like this:

def getContent(self):    c.execute("SELECT HTML FROM Content WHERE conName ='{}'".format(self.contentBox.get()))    fetch = (c.fetchall())    return  # return a list of listsdef setContent(self):    self.clear()    combo = self.getContent()    for row in combo:        # convert list of columns into a string, by joining        # each column with a space        text = " ".join(row)         # write this row, and a newline, to the text widget        self.text_body.insert(END, text + "\n")

This may not be the precise solution for you since I don't know exactly what the data coming back from the database is. The point is that you need to know what type of data the database call is returning (a list of lists), and to do an intelligent job of turning that data into a string.

You could also choose to create a separate function that converts the data, or you could do the conversion in getContent. The important thing is to understand what format your data in in (a list or rows from the database), and what format it needs to be in (string), and do a proper conversion after fetching the data and before passing the data to the text widget.