Python
Topic 5 · Python basics

Strings: Working with Text

Text is everywhere in data. Index and slice strings, use the most useful string methods (strip, lower, split, replace, find, join), format output with f-strings, and handle quotes, new lines and special characters.

Show:
In this topic
Beginner

What a string is

A string is a sequence of characters: letters, digits, spaces, punctuation, even emoji. Write it in single '...' or double "..." quotes (they mean the same; pick one and be consistent). Use three quotes """...""" for text that spans several lines.

Names, addresses, messages, file paths, web pages and every column of text in a spreadsheet are strings. In AI, language models work on strings, so text handling is a core skill.

Python
first = "Sita"
last = 'Gurung'
full = first + " " + last      # + joins strings
print(full)
print(len(full))               # number of characters, including the space: 11
print("-" * 20)                # * repeats a string
note = """Line one
Line two"""
print(note)
print("It's easy")             # use double quotes when the text has a '
print('She said "hi"')         # and single quotes when it has a "
Open in playground ↗
Beginner

Indexing: one character at a time

Each character has a position called an index, counted from 0. Negative indexes count from the end: -1 is the last character.

characterPython
index012345
negative-6-5-4-3-2-1

Strings cannot be changed in place (they are immutable): word[0] = "J" is an error. Instead you build a new string, for example "J" + word[1:].

Beginner

Slicing: pieces of a string

A slice text[start:stop] gives the characters from start up to, but not including, stop. Leave out start to begin at the beginning, leave out stop to go to the end. A third number is the step: [::-1] walks backwards and reverses the string.

Python
word = "Python"
print(word[0], word[-1])   # P n
print(word[0:2])           # Py   (positions 0 and 1)
print(word[2:])            # thon (from 2 to the end)
print(word[:-1])           # Pytho (everything but the last)
print(word[::-1])          # nohtyP (reversed)

date = "2026-11-17"
year, month, day = date[:4], date[5:7], date[8:]
print(year, month, day)
Open in playground ↗
Try it

Watch a slice

Step through common slices and see exactly which characters they pick.

Interactive: this part runs in your browser.

Beginner

String methods: the everyday toolkit

A method is a function that belongs to a value, used with a dot: text.upper(). String methods return a new string; the original is never changed, so store the result: name = name.strip().

MethodWhat it doesExample → result
strip()removes spaces (and new lines) at both ends" hi ".strip() → "hi"
lower(), upper(), title()change case"sita".title() → "Sita"
replace(a, b)replaces every a with b"a-b-c".replace("-", "/") → "a/b/c"
split(sep)cuts into a list of pieces"a,b,c".split(",") → ["a", "b", "c"]
sep.join(list)glues a list of strings together", ".join(["a", "b"]) → "a, b"
startswith, endswithTrue/False checks"data.csv".endswith(".csv") → True
find(x), count(x)position of x (−1 if missing), how many times"banana".count("a") → 3
isdigit(), isalpha()is it all digits / all letters?"2026".isdigit() → True

To check whether some text is inside another, use in: "cat" in "concatenate" is True. The Python reference lists every string method with examples.

Python
raw = "   Sita GURUNG , Brisbane  "
name, city = raw.split(",")         # two pieces
name = name.strip().title()          # "Sita Gurung"
city = city.strip()
print(name, "|", city)

email = "[email protected]"
print(email.lower())
print("@" in email, email.endswith(".com"))
user, domain = email.lower().split("@")
print(user, domain)

words = "the quick brown fox".split()   # no argument: split on any spaces
print(words, len(words))
print("-".join(words))
print("the quick brown fox".replace("quick", "slow"))
print("banana".find("n"), "banana".count("an"))
Open in playground ↗
Beginner

f-strings: put values inside text

An f-string has an f before the quote, and anything inside { } is worked out and inserted. It is the clearest way to build text from values, and it converts numbers for you. After a colon you can say how to format the value:

Inside the bracesResultMeaning
{price:.2f}19.502 decimal places
{n:,}1,234,567thousands separators
{rate:.1%}12.5%as a percentage
{name:<10} / {n:>6}paddedleft / right aligned in a fixed width
{x=}x=42name and value: great for debugging
Python
name = "Sita"
items = 3
price = 6.5
print(f"{name} bought {items} items for ${items * price:.2f}")

population = 2780063
print(f"Brisbane: {population:,} people")
print(f"Pass rate: {0.875:.1%}")

for fruit, cost in [("apple", 1.2), ("mango", 3.75), ("kiwi", 0.9)]:
    print(f"{fruit:<8}{cost:>6.2f}")     # a neat little table

x = 42
print(f"{x=}")
Open in playground ↗
Beginner

Special characters

A backslash starts an escape sequence: \n is a new line, \t a tab, \\ a real backslash, \" a quote inside double quotes. Windows file paths are full of backslashes, so write them as raw strings with an r in front, r"C:\Users\sita\data.csv", or use forward slashes, which Python accepts on Windows too.

Python
print("first line\nsecond line")
print("name\tage")
print("Sita\t27")
print("a backslash: \\")
print(r"C:\new\table.csv")        # raw string: backslashes kept as they are
print(repr("tab\there"))          # repr shows the hidden characters
Open in playground ↗
Beginner

Practice: check yourself

Write the code, then press ✔ Check my answer: hidden tests run your code and tell you exactly what is right. ▶ Run just shows the output. Stuck? Use a hint; the solution is there if you need it.

Exercise 1. Clean a name

raw = " sITA gurUNG ". Make clean equal to "Sita Gurung" (no spaces at the ends, each word capitalised) and initials equal to "SG".

Exercise 2. Slice a date

stamp = "2026-11-17T09:45". Use slicing to set year ("2026"), month ("11"), day ("17") and time ("09:45"). Then set nice to "17/11/2026 at 09:45" using an f-string.

Exercise 3. Count the vowels

Set vowels to the number of vowels (a, e, i, o, u, upper or lower case) in text = "Programming In Python Is Fun". (The answer is 7.)

Beginner

Summary

Strings are immutable sequences of characters. Index from 0, slice with [start:stop] (stop not included), clean text with methods like strip, lower, split and replace, and build output with f-strings.

Key words

string
a sequence of characters, written in quotes
index
a position in a sequence, starting at 0
slice
a piece of a sequence: s[start:stop:step]
method
a function that belongs to a value: s.upper()
immutable
cannot be changed in place; methods return new strings
f-string
f"…{value}…": text with values inserted
escape sequence
a backslash code such as \n (new line)

Common mistakes

  • Calling a method and not keeping the result: name.strip() on its own changes nothing; write name = name.strip().
  • Forgetting that the stop index is not included: "Python"[0:3] is "Pyt".
  • IndexError from text[len(text)]: the last index is len(text) - 1, or simply -1.
  • Forgetting the f: "Hello {name}" prints the braces literally.
  • Comparing text without cleaning it: "Yes " == "yes" is False. Use answer.strip().lower() == "yes".
Check yourself

Quiz

1. What is "Brisbane"[0]?

2. What is "Brisbane"[1:4]?

3. s = " hi " then s.strip(). What is s now?

4. What does "a;b;c".split(";") give?

5. What does f"{3.14159:.2f}" give?

6. Which checks whether a file name is a CSV file?

Ready