How does string concatenation work?

Question

In the context of this exercise, how does string concatenation work?

Answer

In string concatenation, each time a string is added, Python allocates memory to fit the total string, and then copies all the strings into that location in memory. So, if you were adding multiple strings together, like

string1 + string2 + ... + stringN

It would do this process during each concatenation, always adding from the very first string each time

string1 + string2
string1 + string2 + string3
...

until it reaches the last added string.

As a result, concatenation with many strings can be inefficient, but for most problems that we will encounter, the time it takes will usually be negligible.

2 Likes

Is there a looping method using which we can concatenate multiple string variables instead of manually adding them up ???

1 Like

Whilst you could use loops there’s a built-in string method for this string.join() which is probably the most effective way to do it. I’d guess that it will pop up in later lessons but if not there are some relevant FAQs on the forums-

Relevant python docs for this method-

https://docs.python.org/2.7/library/stdtypes.html#str.join

2 Likes

Why does this code work for concatenation:

first_string = string1 + string2

second_string = string3 + string4

third_string = string5 + string6

message = first_string + second_string + third_string

And why does this one NOT work:

message = string1 + string2 + string3 + string4 + string5 + string6

Thanks for any tips! Total newbie here.

2 Likes

A post was split to a new topic: What would be the most efficient way to add each string

Type in print(message), which would print all strings to screen via the variable message encapsulating the string1-string6 .

Hm, I was able to work out the code I needed to get it to pass (I believe), minus “defining” the message. I seem to be getting tripped up on that. Any advice?

Oh. I made a custom name for it, when I should of just wrote “message”. Got it.

Hey…I’m confused on how to compile the code…could someone please explain this?

Python is script and does not need to be compiled. That happens in real time when we Run the script. Are you working in a lesson, or in your own environment?

in a lesson…it’s called something else but it’s compiling all the strings together…12/15 hello world lesson

nvm i figured it out

1 Like

The title for this topic includes "string concatenation" in the name. That is the term we use to describe the combining of two or more objects to form a single string.

Concatenation uses the plus sign operator, + between the objects we wish to combine.

a = 42
b = "The meaning of life is, " + str(a) + "."

print (b)  #  The meaning of life is, 42.