Python 3 String Literals

Alright, Python 3 string literals because who doesn’t love talking about strings? If you’re new to programming, a literal is just a fancy way of saying “fixed value” or “data item”. In other words, it’s something that we write in our code and don’t expect to change.

So what are string literals specifically? Well, they’re the text written inside single quotes (‘), double quotes (“”), or triple quotes (”’ or “””). For example:

# This script assigns values to variables using string literals

# Assigning the string 'John Doe' to the variable name
name = 'John Doe'

# Assigning the string "25" to the variable age
age = "25"

# Assigning the string '''Hello there! How's it going?''' to the variable message
message = '''Hello there! How's it going?'''

Notice that we can use either single or double quotes for simple strings, but if our string has a quote inside of it (like in the message example), we need to use triple quotes. This is because Python doesn’t know where the string ends otherwise!

But what about character literals? These are just like regular string literals except they only contain one character. For instance:

# Using triple quotes to create a string with a quote inside
# This is necessary because Python doesn't know where the string ends otherwise
message = """This is a message with a quote inside: "Hello!" """

# Creating character literals using single quotes
# These are just like regular string literals, but only contain one character
letter = 'a'
symbol = '$'
space = ' '

Now, literal collections which is a fancy way of saying “lists”, “tuples”, “dictionaries”, and “sets”. These are all types of data structures that can hold multiple values. For example:

# Defining a list of numbers
numbers = [1, 2, 3]

# Defining a tuple of names
names = ('Alice', 'Bob', 'Charlie')

# Defining a dictionary of scores, with names as keys and scores as values
scores = {'John': 95, 'Jane': 87}

# Defining a set of fruits
fruits = {'apple', 'banana', 'cherry'} # 6+ (Note: Sets are denoted by curly braces and do not have key-value pairs like dictionaries)

And that’s it! String literals and literal collections are some of the most basic concepts in programming, but they’re also incredibly important for building more complex programs. So go ahead and start practicing with them your future self will thank you!

SICORPS