In Python, you can concatenate (combine) strings using the `+` operator. The `+` operator allows you to join two or more strings together, creating a single string containing the combined contents of the individual strings.
# Concatenating strings
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print("Full Name:", full_name)
# Concatenating strings with literals
greeting = "Hello, " + "World!"
print(greeting)
# Concatenating strings with variables and literals
fruit = "apple"
quantity = 3
order_summary = "You ordered " + str(quantity) + " " + fruit + "s."
print(order_summary)
Python also supports the `+=` operator, which is a shorthand for concatenating strings. It updates the value of the original string by adding the new string to it.
# Using the `+=` operator
message = "Hello, "
name = "Alice"
message += name
print(message)
# Concatenating strings with `+=` and literals
result = "The answer is: "
answer = 42
result += str(answer)
print(result)
Understanding string concatenation with the `+` operator allows you to build dynamic strings and construct messages in your Python programs.