Python code optimization: stroka = stroka + str(line) + '\n' in a loop is long running

Question:

I have the following piece of code that takes data from a SQLite database, then loads it (as text) into the client application, but unfortunately the data loading takes a very long time, how can I make it faster?

results = c.execute(select).fetchall()

stroka = ''
for line in results:
    stroka = stroka + str(line) + '\n'

self.ui.textEdit.setText(stroka)

Answer:

I propose to optimize the composition of the text by replacing string concatenation with join :

text = '\n'.join(str(line) for line in results)

or like this:

text = '\n'.join(map(str, results))
Scroll to Top