LESSON 06 · BEGINNER PATH14 min

Basic String Operations

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.

Read characters and slices from strings and apply common string methods.

Before you start: Variables and Types

Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons

Video lesson: Basic String Operations

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    A string is an ordered sequence of characters, so Python can read one position, select a range, and build a changed version. Open the Basic String Operations lesson and look at the value Python Lab. It contains letters and a space. The space counts as a character too, even though it can be easy to overlook on screen. We will use this short example to practice zero-based indexes, slices whose stop position is excluded, and methods that return new values. Before pressing Run, predict what index zero should select. Then look at the slice from index one to four and predict which three characters will appear. Do not rush to memorize the syntax.

  2. 00:42

    Draw a row of character positions and read the code against that row. The same technique works later for longer strings, lists, and text extracted from files. By the end, you will also know why calling upper does not automatically change the original variable. Run the starter and match each result to one line. Index zero selects capital P, the first character. The slice from one up to four selects the characters at positions one, two, and three, spelling yth. Position four is the stop marker and is not included. Calling upper returns a new uppercase string. Calling split without an argument separates the text at whitespace and returns a list of the words Python and Lab.

  3. 01:28

    The last print shows Python Lab again, unchanged. Strings are immutable, so a method such as upper cannot change that existing string in place. If you want the uppercase result stored under text, assign text equal to text dot upper. Now consider the guide's cleaning example. The raw value has spaces on both sides and uppercase letters. Calling strip removes the outer whitespace from a new string, and lower builds a lowercase version. Chaining them gives python, which compares equal to the target string python. But printing raw still reveals the original spaces and capitals. This is useful when comparing text entered by a person, because accidental spaces and capitalization should not always make an answer wrong.

  4. 02:15

    The next guide example uses the identifier PY dash two zero four. A slice from the start to index two selects PY. A slice beginning at index three selects the numeric-looking part, two zero four, as text. Negative one selects the final character, four. A slice can take a range without knowing exactly how long the string is; a negative index reads from the end. The third guide example starts with one comma-separated string, red comma blue comma green. Split with a comma produces a list of three strings. Join with a separator containing spaces and a slash builds a new string from that list, displayed as red slash blue slash green.

  5. 02:59

    Split goes from one string to several pieces; join goes from pieces back to one string. None of these calls changes the original source string. Pause and ask what type each intermediate result has. That question helps you choose what operation can come next. A slice gives a string, split gives a list, and join gives a string again. You can check those types in the console with type if you are unsure. Also notice the choice of separator in split. Without an argument, as in the starter, Python separates on whitespace and treats runs of spaces as a boundary. With a comma argument, it separates specifically at commas.

  6. 03:39

    The matching join uses the text between list items as its separator. Choosing the wrong separator can leave you with one unexpected piece, so inspect the intermediate list before building the final string. Let us use the short word cat to make two common errors visible. Cat has length three, so its positive indexes are zero, one, and two. Reading index three raises IndexError. If you intended the last character, use index two or negative one. Printing the length helps check your position math. The next mistake tries to replace the character at index zero by assigning directly to that position.

  7. 04:20

    Python raises TypeError because a string cannot be changed in place. Build a new value instead: take the letter b and add the slice from index one onward, producing bat, then assign that new string to the variable. This is different from a list, whose existing positions can be replaced. The error names tell you whether you asked for a position that is absent or attempted an operation the type does not allow. Now take the practical task. Set text to Learn Python. Print a slice that starts at the beginning and stops before position five, so it displays Learn. On another line, print an uppercase copy, which displays LEARN PYTHON.

  8. 05:02

    Predict those two results before pressing Run. If your slice includes the space, check the stop position; the fifth position is excluded when the stop is five. If the uppercase line still looks unchanged, check that you actually called upper with parentheses and printed its return value. The task checker also looks for the slice and method call, so a manually typed answer is not the same as computing the result from text. When it passes, answer the quiz. It asks what a slice of Python selects, what upper returns for lab, and whether a call to upper changes the original variable by itself. For one more experiment, change text to Learn Python with two spaces at the start.

  9. 05:45

    Run the same first-five-character slice and notice that whitespace is now part of what you selected. You may need strip before slicing if your data can contain extra spaces. That small variation shows why string operations are often combined in a deliberate order. In the next lessons, these skills will help you inspect input and produce cleaner messages.

Understand the concept

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.

A closer look

Follow the reasoning, inspect each result, then try the suggested changes in the console below.

01 / 03

Clean text in a predictable sequence

Text copied from a form may contain surrounding spaces or inconsistent capitalization. Chaining strip() and lower() makes a normalized value you can compare reliably. The original string remains unchanged because strings are immutable; each method returns another string. Keep the raw value if you might need to show exactly what the user entered.

The example keeps both raw and cleaned names so you can see the difference. Predict the Boolean before running it. Then change the raw text to include a trailing exclamation mark: trimming spaces and changing case will not remove that punctuation. Cleaning rules should match the actual input your program expects.

PYTHON
raw = "  PYTHON  "
cleaned = raw.strip().lower()
print(cleaned)
print(cleaned == "python")
print(raw)
EXPECTED OUTPUT
python
True
  PYTHON  
Follow the reasoning
  1. strip removes spaces from both ends, but not from the middle.
  2. lower returns a lowercase version of the trimmed text.
  3. raw still contains its original spaces and capital letters.
02 / 03

Extract meaningful parts of an identifier

A string's positions make it possible to pull out a prefix or suffix when the text follows a known format. With a code such as PY-204, the first two characters identify a category and everything after the dash is a number written as text. A slice includes its start and excludes its stop.

Hard-coded positions are reasonable only when the format is fixed. If prefixes vary in length, splitting at the dash is more robust than guessing an index. For this exact format, predict what code[-1] will display, then change 204 to 305 and compare the extracted pieces. Always inspect the shape of incoming data before slicing it.

PYTHON
code = "PY-204"
print(code[:2])
print(code[3:])
print(code[-1])
EXPECTED OUTPUT
PY
204
4
Follow the reasoning
  1. [:2] selects indexes 0 and 1, stopping before 2.
  2. [3:] starts just after the dash and continues to the end.
  3. [-1] selects the final character.
03 / 03

Split one string into pieces, then join it back

A separator lets one line of text carry several values. split(',') divides a comma-separated string into a list of pieces. join does the reverse kind of operation: it combines a sequence of strings with a chosen separator between them. This is handy for a small display label or a quick export format.

Neither call changes the original source string. The example takes three colors and displays them with slashes. Predict how many list items split creates, then change the comma in the source to a semicolon without changing the split argument. The result shows why the separator must match the data. For full CSV files, use Python's csv module instead.

PYTHON
source = "red,blue,green"
colors = source.split(",")
print(colors)
print(" / ".join(colors))
EXPECTED OUTPUT
['red', 'blue', 'green']
red / blue / green
Follow the reasoning
  1. split creates a three-item list using commas as boundaries.
  2. join inserts ' / ' between adjacent items.
  3. The source string remains 'red,blue,green'.

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.

    Browse this lesson’s problem fixes