Introduction
In this lab, you will explore the fundamental techniques for manipulating strings in Python. Strings are one of the most common data types, and knowing how to work with them effectively is a crucial skill for any Python programmer. We will cover everything from basic definitions, using special characters, and creating multiline strings to more advanced operations like accessing substrings, checking for content, changing case, searching, splitting, and formatting text. By the end of this lab, you will have a solid foundation for handling text data in your Python programs.
Escape Characters and Multiline Strings
In this step, you will learn how to handle special characters within strings, create strings that ignore these special characters, and define strings that span multiple lines.
First, let's explore escape characters. An escape character is a backslash \ followed by a character that you want to insert. For example, \n represents a newline, and \' represents a single quote.
Note: If you are not familiar with using WebIDE (VS Code like), please learn it first at this lab.
Open the main.py file from the file explorer on the left. Add the following code to it:
## Escape characters: use backslash to insert special characters
## \n = newline, \' = single quote
print("Hello there!\nHow are you?\nI\'m doing fine.")
Now, run the script by opening a terminal and executing the command below. You can open a new terminal by clicking the + icon in the terminal panel.
python3 main.py
You will see the output with newlines and a single quote inserted correctly.
Hello there!
How are you?
I'm doing fine.
Next, let's look at raw strings. A raw string, prefixed with an r, ignores all escape characters and prints any backslash that appears in the string. This is particularly useful for regular expressions or file paths.
Replace the content of main.py with the following code:
## Raw string (r prefix): treats backslashes as literal characters
print(r"Hello there!\nHow are you?\nI\'m doing fine.")
Run the script again:
python3 main.py
Notice how the \n and \' are now treated as literal characters in the output.
Hello there!\nHow are you?\nI\'m doing fine.
Finally, you can create multiline strings using triple quotes (""" or '''). This is a convenient way to define strings that span several lines, preserving the formatting.
Replace the content of main.py with this example:
print(
"""Dear Alice,
Eve's cat has been arrested for catnapping,
cat burglary, and extortion.
Sincerely,
Bob"""
)
Execute the script:
python3 main.py
The output will be a formatted, multiline message.
Dear Alice,
Eve's cat has been arrested for catnapping,
cat burglary, and extortion.
Sincerely,
Bob
Indexing and Slicing Strings
In this step, you'll learn how to access individual characters and extract substrings using indexing and slicing.
Strings in Python are sequences, which means you can access their parts using an index. Indexing starts at 0 for the first character.
H e l l o w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11
Clear the main.py file and add the following code to define a string:
spam = 'Hello world!'
To access the first character ('H'), you use index 0. To access the fifth character ('o'), you use index 4. You can also use negative indices to count from the end of the string; -1 refers to the last character.
Add these print statements to main.py to see indexing in action:
spam = 'Hello world!'
## String indexing: access characters by position (0-based)
print(spam[0]) ## Returns first character
print(spam[4]) ## Returns fifth character
print(spam[-1]) ## Returns last character
Run the script:
python3 main.py
The output will show the individual characters you accessed.
H
o
!
Slicing allows you to extract a portion of a string, called a substring. The syntax is [start:end], which extracts characters from the start index up to, but not including, the end index.
Let's practice slicing. Replace the content of main.py with the following code. We'll explore a few different ways to slice the string.
spam = 'Hello world!'
## String slicing: extract substring using [start:end] syntax
print(spam[0:5]) ## Returns characters from index 0 to 4
print(spam[:5]) ## Omitting start index defaults to 0
print(spam[6:]) ## Omitting end index defaults to the end of the string
print(spam[::-1]) ## A step of -1 reverses the string
Execute the script:
python3 main.py
Observe the different substrings created by slicing.
Hello
Hello
world!
!dlrow olleH
String Membership and Case Methods
In this step, you will learn how to check if a substring exists within a string and how to change and validate the case of a string.
The in and not in operators are used to check for string membership. They return a boolean value: True or False.
Clear the main.py file and add the following code to test these operators. Note that the comparison is case-sensitive.
## The 'in' and 'not in' operators
print('Hello' in 'Hello World')
print('HELLO' in 'Hello World')
print('cats' not in 'cats and dogs')
Run the script to see the boolean results:
python3 main.py
True
False
False
Python also provides several methods to change the case of a string. The upper(), lower(), and title() methods return a new string in all uppercase, all lowercase, or title case (where each word is capitalized), respectively.
Replace the content of main.py with the following:
greet = 'Hello world!'
print(greet.upper())
print(greet.lower())
print(greet.title())
Execute the script:
python3 main.py
You will see the transformed strings.
HELLO WORLD!
hello world!
Hello World!
To check if a string is already in a specific case, you can use the isupper() and islower() methods. These methods return True if all cased characters in the string are of the specified case and there is at least one cased character.
Replace the content of main.py with these examples:
spam = 'Hello world!'
print(spam.islower())
print('HELLO'.isupper())
## This is true because non-letter characters are ignored
print('abc12345'.islower())
## This is false because there are no cased characters
print('12345'.islower())
Run the script to verify the case of each string.
python3 main.py
False
True
True
False
Searching and Splitting Strings
In this step, you'll learn how to check if a string starts or ends with a specific substring, how to join a list of strings into a single string, and how to split a string into a list of substrings.
The startswith() and endswith() methods are useful for checking the beginning or end of a string. They return True or False.
Clear main.py and add the following code:
print('Hello world!'.startswith('Hello'))
print('Hello world!'.endswith('world!'))
print('abc123'.startswith('abcdef'))
Run the script to see the results:
python3 main.py
True
True
False
The join() method is called on a separator string and takes an iterable (like a list) as an argument. It combines the elements of the iterable into a single string, with the separator placed between each element.
Replace the content of main.py with these examples to see how join() works:
## Join with a comma and space separator
print(', '.join(['cats', 'rats', 'bats']))
## Join with a space separator
print(' '.join(['My', 'name', 'is', 'Simon']))
Execute the script:
python3 main.py
cats, rats, bats
My name is Simon
The split() method does the opposite of join(). It is called on a string and breaks it into a list of substrings. By default, it splits on whitespace, but you can provide a specific delimiter.
Replace the content of main.py with the following code to practice splitting strings:
## Split by default whitespace
print('My name is Simon'.split())
## Split by a specific delimiter 'ABC'
print('MyABCnameABCisABCSimon'.split('ABC'))
Run the script to see the resulting lists:
python3 main.py
['My', 'name', 'is', 'Simon']
['My', 'name', 'is', 'Simon']
Justifying and Cleaning Strings
In this step, you will learn how to format string alignment and how to remove unwanted characters, such as whitespace, from the beginning or end of a string.
Python provides methods to justify text within a given width: rjust() (right-justify), ljust() (left-justify), and center(). These methods return a new padded string.
Clear the main.py file and add the following code:
print('Hello'.rjust(10))
print('Hello'.ljust(10))
print('Hello'.center(20))
Run the script to see the aligned text. The single quotes in the output help visualize the padding.
python3 main.py
Hello
Hello
Hello
You can also provide an optional second argument to specify a fill character other than a space. Replace the content of main.py with this:
print('Hello'.rjust(20, '*'))
print('Hello'.center(20, '='))
Run the script again:
python3 main.py
***************Hello
=======Hello========
To clean up strings, you can use the strip(), rstrip(), and lstrip() methods. These are used to remove characters from the ends of a string. By default, they remove whitespace characters (spaces, tabs, newlines).
Replace the content of main.py with this example:
spam = ' Hello World '
print(spam.strip()) ## Removes from both ends
print(spam.lstrip()) ## Removes from the left side
print(spam.rstrip()) ## Removes from the right side
Execute the script to see the cleaned strings:
python3 main.py
Hello World
Hello World
Hello World
You can also pass a string argument to these methods to specify which characters to remove. The method will remove all characters from the argument that are at the ends of the string.
Replace the content of main.py one last time:
spam = 'SpamSpamBaconSpamEggsSpamSpam'
## Removes all characters 'S', 'p', 'a', 'm' from the ends
print(spam.strip('ampS'))
Run the script:
python3 main.py
The output shows that the outer "Spam" parts have been removed, leaving the central part of the string.
BaconSpamEggs
Summary
In this lab, you have mastered the essential techniques for string manipulation in Python. You learned how to use escape characters and create multiline strings for better text representation. You practiced accessing parts of a string using indexing and slicing. You also explored powerful string methods for checking membership (in, not in), changing case (upper(), lower()), validating case (isupper(), islower()), searching (startswith(), endswith()), joining and splitting, and finally, formatting and cleaning text (rjust(), strip()). These skills are fundamental for any task involving text processing in Python.



