To kick things off: what are string literals? Well, they’re basically just strings that you write down in your code. You can use single quotes (like ‘hello’), double quotes (“world”), or even triple quotes (”’python is awesome!”’) to create them. Here’s an example:
# String literal is a sequence of characters enclosed in quotes, used to represent text in Python.
# Assigning the string "John Doe" to the variable name.
name = "John Doe"
# Printing the value of the variable name.
print(name)
Now, concatenation the process of joining two strings together.In Python, you can do this by using the ‘+’ operator (which is not to be confused with adding numbers). Here’s an example:
# Concatenating strings
# The process of joining two strings together.
# Declaring variables
first_name = "John" # Declaring a variable 'first_name' and assigning it the string value "John"
last_name = "Doe" # Declaring a variable 'last_name' and assigning it the string value "Doe"
# Concatenating strings
full_name = first_name + " " + last_name # Concatenating the strings 'first_name' and 'last_name' with a space in between and assigning it to the variable 'full_name'
# Printing the full name
print(full_name) # Printing the value of the variable 'full_name' which is "John Doe"
But what if you want to join multiple strings together that are already in variables? No problem! Just use the ‘+’ operator again:
# This script is used to join multiple strings together that are already in variables.
# Define the variable "greeting" and assign it the string value "Hello, "
greeting = "Hello, "
# Define the variable "name" and assign it the string value "John Doe"
name = "John Doe"
# Define the variable "message" and assign it the concatenated value of "greeting" and "name"
message = greeting + name
# Print the value of "message"
print(message)
Now, a cool feature that was added in Python 3.6 formatted string literals! This allows you to insert variables directly into your strings without having to concatenate them separately:
# This script uses formatted string literals to insert variables into a string without concatenation
# Define variables for name and age
name = "John Doe"
age = 25
# Create a message using the formatted string literal, inserting the variables
message = f"My name is {name} and I am {age} years old."
# Print the message
print(message)
And that’s it! String literals and concatenation are two of the most fundamental concepts in Python, but they can be a bit tricky to understand at first. Just remember: use quotes to create strings, and ‘+’ to join them together (or f-strings for formatted string literals).