Python Strings

String concatenation and formatting

1. Combining strings using the + Operator:

The plus operator (+) is the most straightforward way to combine strings. It creates a new string by joining the original strings together.

first_name = "Alice"
last_name = "Smith"

full_name = first_name + " " + last_name
print(full_name)  # Output: Alice Smith

In this example, three strings are concatenated: "Alice", a space (" "), and "Smith", resulting in the full name "Alice Smith".


2. String formatting with f-strings (formatted string literals):

Introduced in Python 3.6, f-strings (formatted string literals) are a powerful and readable way to embed variables or expressions directly within strings. You enclose the string in curly braces {} and place the variable or expression you want to include there.

name = "Bob"
greeting = f"Hello, {name}! How are you today?"
print(greeting)  # Output: Hello, Bob! How are you today?

Here, the name variable is inserted into the string using curly braces, resulting in a personalized greeting.


3. Older formatting methods (.format() and % operator) :

While f-strings are generally preferred for their readability and flexibility, here's a brief mention of older formatting methods:

  • .format() : This method allows you to insert placeholders ({}) within the string and provide the values as arguments to the .format() method call.

name = "Charlie"
message = "Welcome, {}!".format(name)
print(message)  # Output: Welcome, Charlie!

  • % operator: The modulo operator (%) is an older formatting technique that uses placeholders (%s for strings, %d for integers, etc.) within the string and provides the values separately. This method can be less readable and is generally discouraged in favor of f-strings or the .format() method.

name = "David"
salutation = "Hi, %s" % name
print(salutation)  # Output: Hi, David


Notes:
f-strings are the recommended approach for string formatting in Python 3.6 and above due to their clarity and ease of use.

It's time to take a quiz!

Test your knowledge and see what you've just learned.

Which operator is used to combine two strings in Python?

The + operator
The * operator
The & operator
Check Answer

What is the recommended string formatting method in Python 3.6 and above?

The % operator
f-strings
The .format() method
Check Answer

What is the output of: first_name = "Alice"; last_name = "Smith"; full_name = first_name + " " + last_name?

"Alice"
"Smith"
"Alice Smith"
Check Answer

Which method uses {} placeholders to insert variables into a string?

f-strings
The .format() method
The % operator
Check Answer

Which operator is used in older Python versions for string formatting and uses %s for strings?

The + operator
The .format() method
The % operator
Check Answer