Basic String Operations
Read characters and slices from strings and apply common string methods.
Video coming to YouTube
Work through the full lesson and run its code while the video is being prepared for publication.
Understand the concept
Strings are ordered sequences of characters. Their indexes start at 0. A slice such as text[1:4] includes the start index and stops before index 4.
Methods such as upper(), lower(), strip(), and split() return useful results. Strings are immutable, so a method that changes the appearance of text returns a new string instead of changing the original.
- Index and slice text
- Slice stop is excluded
- String methods return new values
See it step by step
Read the code, predict the output, then compare it with the result.
01. Take two slices
text = "Python Lab"
print(text[:6])
print(text[-3:])Python
LabThe first slice stops before index 6; the negative start counts from the end.
02. Make new strings
phrase = "learn python"
print(phrase.title())
print(phrase.replace("python", "coding"))Learn Python
learn codingString methods return new text. The original phrase is still unchanged.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Assign text = 'Learn Python'. A slice ending at 5 returns the first five characters; text.upper() returns the uppercase copy.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Index outside a string
word = "cat"
print(word[3])word = "cat"
print(word[2])What happens: IndexError because valid positive indexes are 0, 1, and 2.
The last positive index is one less than the string length.
Changing a character in place
word = "cat"
word[0] = "b"word = "cat"
word = "b" + word[1:]
print(word)What happens: TypeError because strings cannot be changed in place.
Construct a new string and assign it to the variable.