Python:
Concatenating strings
How to:
Let’s smash some strings together.
first_name = "Charlie"
last_name = "Brown"
full_name = first_name + " " + last_name # Classic concatenation with a space
print(full_name)
Output: Charlie Brown
Using join()
for a list of words:
words = ["Hello", "world!"]
sentence = " ".join(words)
print(sentence)
Output: Hello world!
F-String (since Python 3.6):
user = "snoopy"
action = "flying"
log_message = f"{user} is {action} his doghouse"
print(log_message)
Output: snoopy is flying his doghouse
Deep Dive
Concatenation has been a fundamental string operation since the dawn of programming. Remember, Python treats strings as immutable, so every concatenation creates a new string.
Once, the plus (+
) was all we had. Not efficient for multiple strings, as it could lead to memory bloat and slow performance. Cue the join()
method—more memory-friendly, especially for fusing a series of strings.
F-Strings, introduced in Python 3.6, are a game changer. They’re readable and fast and allow expression evaluation within string literals—f"{variable}"
. They’re the go-to for a modern Pythonista, blending functionality and efficiency.