Today we’re going to talk about something that might seem trivial but is actually pretty ***** important: string literals in Python.
First off, let’s start with the basics. A string literal is a fixed sequence of characters enclosed in quotes (either single or double). For example:
# Define a variable "name" and assign it the string value "GeeksforGeeks"
name = "GeeksforGeeks"
# Print the value of the variable "name"
print(name) # Output: GeeksforGeeks
That’s pretty straightforward, right? But what if you want to include a quote inside your string literal? Well, that’s where things get interesting. You can use either single or double quotes for this purpose it doesn’t matter which one you choose! Here are some examples:
# Define a variable named "quote" and assign it a string value
quote = "He said, 'Python is awesome!'"
# Print the value of the "quote" variable
print(quote) # Output: He said, 'Python is awesome!'
# The purpose of this script is to demonstrate how to include a quote inside a string literal using either single or double quotes.
But what if you want to use both single and double quotes in your string? No problem! Just switch between them as needed. Here’s an example:
# Using a mix of single and double quotes inside the string literal
mixed_quotes = 'He said, "I love Python"!' # Changed double quotes to single quotes for consistency
print(mixed_quotes) # Output: He said, "I love Python"!
Now triple-quoted strings. These are great for writing multi-line strings without having to worry about escaping newlines or other special characters. Here’s an example:
# This script is used to print a poem using a multi-line string literal and the print function.
# The poem variable is assigned a string value using triple quotes to allow for a multi-line string.
poem = """Roses are red,
Violets are blue,
Sugar is sweet,
And so are you!"""
# The print function is used to output the value of the poem variable.
print(poem)
# Output:
# Roses are red,
# Violets are blue,
# Sugar is sweet,
# And so are you!
That’s it for our tutorial on Python string literals. Hopefully this has been helpful and entertaining (or at least mildly amusing)! Remember to always use the appropriate quote type when writing your strings whether that be single quotes or double quotes, depending on your preference. And if you ever need to include both in a single string literal, just switch between them as needed.