Python:
שרשור מחרוזות

How to: איך לעשות זאת

In Python, concatenating strings can be done in several ways:

  1. Using the + operator:
greeting = "שלום"
name = "עולם"
message = greeting + " " + name
print(message)  # Outputs: שלום עולם
  1. With the join method:
words = ["שלום", "עולם"]
message = " ".join(words)
print(message)  # Outputs: שלום עולם
  1. By using f-strings (Python 3.6+):
name = "עולם"
message = f"שלום {name}"
print(message)  # Outputs: שלום עולם
  1. Or even string interpolation with %:
name = "עולם"
message = "שלום %s" % name
print(message)  # Outputs: שלום עולם

Deep Dive: צלילה לעומק

String concatenation has been in Python since the very beginning. Early on, using the + operator was the straightforward method, but it’s not the most efficient, especially for large amount of strings – it can be slow and consume more memory. That’s because strings in Python are immutable, meaning each time you concatenate, a new string is created.

The join method is much more memory-efficient for concatenation of large lists or when working within loops. Why? It allocates memory for the new string only once.

F-strings, introduced in Python 3.6, brought a cleaner and more readable way to include expressions inside string literals, efficiently combining both syntax simplicity and performance.

Alternatives like string interpolation with % are considered legacy but are still in use for specific cases or by those who prefer them over the newer syntax.

See Also: ראו גם