LESSON 06 · BEGINNER PATH10 min

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

PYTHON
text = "Python Lab"
print(text[:6])
print(text[-3:])
EXPECTED OUTPUT
Python
Lab

The first slice stops before index 6; the negative start counts from the end.

02. Make new strings

PYTHON
phrase = "learn python"
print(phrase.title())
print(phrase.replace("python", "coding"))
EXPECTED OUTPUT
Learn Python
learn coding

String 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 run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnChange text to "Learn Python". Print its first five characters and then print an uppercase version.
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.

    01.What is "Python"[1:4]?

    02.What is "lab".upper()?

    03.After word = "Hi"; word.upper(), what is word?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Index outside a string

    COMMON MISTAKE
    word = "cat"
    print(word[3])
    FIX
    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

    COMMON MISTAKE
    word = "cat"
    word[0] = "b"
    FIX
    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.