Course contentsShow
← Python
Lesson 39 of 1,0601. Foundations and EnvironmentFree lesson

Constructing and Manipulating String Literals

Create string objects using single or double quotes and understand how to handle special characters using appropriate escape sequences.

Constructing and Manipulating String Literals

In this lesson, you will learn how to define text in Python using string literals and how to include special characters using escape sequences.

Creating Strings

In Python, a string is a sequence of characters, and you create one by wrapping your text in either single quotes (') or double quotes ("). Both are perfectly valid and function the same way.

# Using single quotes
greeting = 'Hello, Python!'

# Using double quotes
message = "Welcome to your 39th lesson."

Handling Special Characters

Sometimes, your text needs to include characters that might confuse Python, such as a quote mark inside a string. If you used a single quote to start your string, Python thinks any other single quote marks the end of it. To tell Python to treat that quote as literal text rather than the end of the string, we use the backslash (\) as an escape character.

For example, if you want to write the word "it's" inside a single-quoted string, you must escape the internal quote:

# Escaping a single quote inside a single-quoted string
text = 'It\'s a beautiful day.'

# You can also just use double quotes to avoid the escape character
alternative = "It's a beautiful day."

The backslash tells Python: "Don't treat the next character as code; just treat it as part of the text." You can also use this for special formatting, such as \n to create a new line:

# Using a newline escape sequence
poem = "Roses are red,\nViolets are blue."
print(poem)

In this example, \n doesn't print the letters "n"; instead, it tells the computer to jump to the next line. By choosing your quotes wisely or using the backslash, you gain full control over how your text appears.

Key Takeaway: String literals can be created with either single or double quotes, and the backslash escape character allows you to include special characters like internal quotes or newlines within your text.