Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (Retired) Ins & Outs String Concatenation

Ali Mammadov
Ali Mammadov
2,172 Points

String concatenation performance in Python

Is there a more efficient, in terms of used resources, way to concatenate strings in Python?

2 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Are you just trying to join a bunch of strings together? .join() is probably faster & more memory efficient than +.

That said, string concatenation in Python isn't very inefficient since the GC is pretty solid.

Ali Mammadov
Ali Mammadov
2,172 Points

Are there any alternatives to .join()?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Not really. You could do it the slower and concatenation way.

final_string = ''
for string in list_of_strings:
    final_string += string

Are you really in a position where you need to optimize this? If you're not, don't waste time on it.

Ali Mammadov
Ali Mammadov
2,172 Points

Believe me, I am! I have came to a few versions. How do you think, which of them will be the fastest?

cdmp = "%(BIN)s%(CC)s%(EXP)s%(HLDR)s" % locals()
cdmp = "{BIN}{CC}{EXP}{HLDR}".format(**locals())
parts = []
for CRD in avg_dmp:
    avg_dmp.append(rtvr_nums(CRD))
cdmp = "".join(avg_dmp)
Vittorio Somaschini
Vittorio Somaschini
33,371 Points

Hello Ali.

I think that is the way to do concatenation in Python, but in the following videos you will discover a way to put variables inside strings using placeholders and .format().

I am pretty sure you will like it!

;)

Ali Mammadov
Ali Mammadov
2,172 Points

But string concatenation eats a lot of memory, because it creates useless duplicates of strings in RAM. How can I get rid of this? I'm trying to concatenate pretty big strings (>500 characters each).