Free preview
100 lessons
Python Done Right
Free preview
Python Done Right · 100 lessons
No surprise gaps
Actually remember it
Skip what you know
One subscription. All learning paths included.
Our content is best on a larger screen
Creating strings from literal values
Strings are sequences of characters enclosed in quotes. A string literal is created by placing characters between quotes:
single_quoted = 'This uses single quotes.'
double_quoted = "This uses double quotes."
print(single_quoted) # Output: This uses single quotes.
Single and double quotes are interchangeable. Having both allows us to embed one type inside the other:
message = "It's a lovely day" # Apostrophe inside double quotes
quote = 'He said "hello"' # Double quotes inside single quotes
nested = "'Python'" # Single quotes as part of the string
Multi-line strings
For strings spanning multiple lines, use triple quotes (''' or """):
multi_line = '''This string
spans multiple
lines.'''
also_valid = """Triple quotes work
for multi-line text."""
single_line_triple_quote = """This is also valid"""
Triple quotes preserve line breaks in the output.
Escape sequences
To include special characters in a string, use the backslash (\) as an escape character. When printed, these sequences produce:
| Sequence | Produces | Example |
|---|---|---|
\\ | Single backslash | "C:\\Users" → C:\Users |
\' | Apostrophe | 'It\'s' → It's |
\" | Double quote | "He said \"hi\"" → He said "hi" |
\n | Newline | "A\nB" → A then B on next line |
\t | Tab | "A\tB" → A B |
Warning
We cannot mix quote types for a single string. For example, "hello' is invalid and raises a SyntaxError.
Embedding quotes
Use double quotes to include an apostrophe, or single quotes to include double quotes:
print("It's raining") # Apostrophe inside double quotes
print('She said "hello"') # Double quotes inside single quotes
Output:
It's raining
She said "hello"
Escape sequences
Use backslash to insert special characters like newlines, tabs, and literal backslashes:
print("Line 1\nLine 2") # \n = newline
print("Name:\tAlice") # \t = tab
print("C:\\Users\\name") # \\ = literal backslash
print('It\'s also valid') # \' = apostrophe in single-quoted string
Output:
Line 1
Line 2
Name: Alice
C:\Users\name
It's also valid
Notice that \n, \t, \\, and \' don't appear literally in the output - they produce a newline, tab, single backslash, and apostrophe respectively.
Practice questions
5 questions
In the Python Console, create a variable named answer and assign the string literal "Python Programming" to it.
Once done, press submit.
+ 4 more questions
Concatenating and repeating strings
Two basic string operations are concatenation and repetition.
Concatenation joins strings end-to-end using the + operator:
"Hello" + "World" # Result: "HelloWorld"
Repetition repeats a string using the * operator with an integer:
"echo" * 3 # Result: "echoechoecho"
Warning
We can only concatenate strings with strings. Trying "Hello" + 4 raises a TypeError.
Building a full name
first_name = "John"
last_name = "Doe"
full_name = first_name + last_name
print(full_name) # Output: JohnDoe
The names are joined directly with no space between them.
Adding a space
To separate the names, we concatenate an extra space string:
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
Repeating strings
word = "echo"
repeated = word * 3
print(repeated) # Output: echoechoecho
Combining both
We can use concatenation and repetition together:
result = "ha" * 3 + "!"
print(result) # Output: hahaha!
Practice questions
5 questions
In the Python Console, there are two string variables defined: quote_part_1 and quote_part_2.
Concatenate the two variables to form a valid quote and assign the result to a variable named answer.
Once done, press submit.
+ 4 more questions
Basic string methods
Strings have built-in methods we can call using dot notation: string.method_name(). Each method returns a new string (the original is unchanged).
Case conversion
.lower() - converts all characters to lowercase.upper() - converts all characters to uppercaseWhitespace and characters
.strip() - removes leading and trailing whitespace (or specified characters)Searching
.find(substring) - returns the index of the first occurrence, or -1 if not found.startswith(substring) - returns True if the string starts with the substring.endswith(substring) - returns True if the string ends with the substringReplacing
.replace(old, new) - replaces all occurrences of old with newInfo
These methods also work directly on string literals: "hello".upper() returns "HELLO". We can also chain methods: " HELLO ".lower().strip() returns "hello".
Case conversion
text = "Hello World!"
print(text.lower()) # Output: hello world!
print(text.upper()) # Output: HELLO WORLD!
Stripping whitespace
text = " Hello World! "
print(text.strip()) # Output: Hello World!
We can also strip specific characters:
text = "!!Hello World!!"
print(text.strip('!')) # Output: Hello World
Note: .strip() only removes from the start and end, not the middle.
Finding substrings
text = "Hello World"
print(text.find("World")) # Output: 6
print(text.find("Python")) # Output: -1
Checking start and end
text = "Hello World"
print(text.startswith("Hello")) # Output: True
print(text.endswith("World")) # Output: True
print(text.endswith("world")) # Output: False (case-sensitive)
Replacing substrings
text = "Hello, World"
print(text.replace("World", "Python")) # Output: Hello, Python
Practice questions
4 questions
In the Python Console there's a string variable defined called text.
Strip any leading and trailing whitespace from the variable text and assign to a variable named answer.
Once done, press submit.
+ 3 more questions