Thuta Learning
Python
BasicProgrammingBeginner

Python Strings

PythonLesson 1025 min

What you'll walk away with

  • Choose between single, double and triple quotes
  • Predict the result of positive and negative indexes and [start:stop] slices
  • Understand that string methods return a new string and store that result
  • Insert variables into text with f-strings and measure length with len()

Explain it simply

Explain it simply

A string is text: a sequence of characters lined up in order. Names, email addresses, messages and file paths are all strings. In Python you write text inside 'single quotes', "double quotes" or """triple quotes""".

Every character has a position number, its index, starting at 0, so "Python"[0] is "P". You cut out pieces of text with slices, and you use methods for jobs such as changing case or removing spaces.

Problem → Why → Solution

The problem: strip() was called, yet the login still fails

On a login form the user types " Aye " with spaces and a capital letter. The developer calls strip() and lower(), yet the username never equals "aye". With no error to point at, the bug is hard to find: the methods did run, but their results were thrown away.

login.py
username = "  Aye "

username.strip()          # result is discarded
username.lower()          # result is discarded

print(username == "aye")  # False
print(repr(username))     # '  Aye '

Why didn't it change?

Python strings are immutable: once created, their characters can never be changed. Every method such as strip() or lower() leaves the original alone and returns a brand-new string. You only keep the change by assigning the result back, for example username = username.strip().lower().

Core concept: a string is an immutable sequence of characters

'Hello' and "Hello" are exactly the same. Double quotes are handy when the text contains an apostrophe ("It's fine"), and triple quotes hold text that spans several lines. Inside a string, \n stands for a new line and \t for a tab.

text
Indexes of "Python"
-------------------
 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5      positive index
  -6  -5  -4  -3  -2  -1      negative index

 text[0:3] -> "Pyt"   (stop index 3 is NOT included)
 text[2:]  -> "thon"  (from index 2 to the end)

Indexes start at 0, and negative indexes count from the end, so -1 is the last character. A slice text[start:stop] includes start but excludes stop, which is why text[0:3] returns three characters. Leave out start to begin at the front, or leave out stop to run to the end. A single index past the end (text[10]) raises IndexError, but a slice simply returns whatever exists, without an error.

Because strings are immutable, text[0] = "J" raises TypeError: 'str' object does not support item assignment. upper(), lower(), strip() and replace() return new strings, while split() returns a list. Called without an argument, split() breaks the text on any run of whitespace and ignores spaces at both ends.

Inside an f"..." string, the {} placeholders can hold variables or whole expressions, and Python turns values of any type into text. len() returns the number of characters, and the in operator, as in "py" in "python", tests whether a substring is present.

Strings can be joined with + and repeated with *: "Py" + "thon" is "Python" and "ab" * 3 is "ababab". Every Python 3 string is Unicode, so Myanmar text and emoji are stored without any trouble. One thing to watch is that len() counts Unicode code points, not the letters your eye sees. The word "မြန်မာ" looks like three syllables, yet its consonants, vowel signs and the asat mark add up to len() == 6.

Mental model: keep the new string
  1. Index 0 is first, -1 is last
  2. A slice includes start, not stop
  3. A method returns a new string
  4. Assign the result to keep it

You never edit a string in place; you always get back a modified copy.

General pattern

python
text = "some text"
char = text[index]            # one character, index from 0
part = text[start:stop]       # stop is excluded
last = text[-1]               # count from the end

new_text = text.method(args)  # methods return a NEW string
words = text.split()          # -> list of words

message = f"{name} is {age} years old"
size = len(text)

Indexing and slicing read characters, methods produce new strings, and f-strings insert variables. Store a method's result in a new variable such as new_text or back in the original one.

Example: create, slice, transform and format

This example creates strings with all three quote styles, then indexes and slices "Python". Next it tries five methods on " hello world ", which has spaces at both ends. In the output, notice that upper() and replace() keep the leading spaces and only strip() removes them.

strings.py
# ===== 1. String Creation =====
a = 'Hello'
b = "World"
c = """This is
a multi-line
string"""

print(f"Single quotes: {a}")
print(f"Double quotes: {b}")
print(f"Multi-line: {c}")

# ===== 2. String Indexing & Slicing =====
print("\n===== Indexing & Slicing =====")
text = "Python"
print(f"First character: {text[0]}")    # P
print(f"Last character: {text[-1]}")    # n
print(f"Slice [0:3]: {text[0:3]}")      # Pyt
print(f"Slice [2:]: {text[2:]}")        # thon

# ===== 3. String Methods =====
print("\n===== String Methods =====")
txt = "  hello world  "
print(f"Upper: {txt.upper()}")
print(f"Lower: {txt.lower()}")
print(f"Strip: '{txt.strip()}'")
print(f"Replace: {txt.replace('world', 'Python')}")
print(f"Split: {txt.split()}")

# ===== 4. String Formatting (f-strings) =====
print("\n===== String Formatting =====")
name = "Sai"
age = 25
print(f"My name is {name}, I am {age} years old.")

# ===== 5. String Length =====
print(f"\nLength of 'Python': {len('Python')}")

Code breakdown

  1. Lines 4-6c = """This is

    Triple quotes keep the line breaks you type, so printing c produces three lines.

  2. Line 16print(f"Last character: {text[-1]}") # n

    -1 is the last character, so there is no need for text[len(text) - 1].

  3. Line 17print(f"Slice [0:3]: {text[0:3]}") # Pyt

    It takes indexes 0, 1 and 2 and stops before 3, giving "Pyt"; the length is stop - start = 3.

  4. Line 25print(f"Strip: '{txt.strip()}'")

    Printing between quotes makes it visible that the spaces at both ends are gone, while txt itself stays unchanged.

  5. Line 27print(f"Split: {txt.split()}")

    split() with no argument breaks on whitespace and returns ['hello', 'world'], with no empty strings.

You should see
Single quotes: Hello
Double quotes: World
Multi-line: This is
a multi-line
string

===== Indexing & Slicing =====
First character: P
Last character: n
Slice [0:3]: Pyt
Slice [2:]: thon

===== String Methods =====
Upper:   HELLO WORLD
Lower:   hello world
Strip: 'hello world'
Replace:   hello Python
Split: ['hello', 'world']

===== String Formatting =====
My name is Sai, I am 25 years old.

Length of 'Python': 6

Slices with a step, and methods that ask questions

A slice accepts a third value, the step: text[::2] takes every second character and text[::-1] reverses the string. Besides methods that transform text, there are methods that ask questions. startswith(), endswith() and isdigit() return True or False, find() returns the index of a substring (or -1 if it is missing), and count() says how many times it appears. The opposite of split() is "-".join(list), which glues a list of strings together with a separator between them.

string_tools.py
text = "Python"
print(text[::2])                  # Pto
print(text[::-1])                 # nohtyP
print("report.pdf".endswith(".pdf"))   # True
print("2024".isdigit())           # True
print("banana".find("na"), "banana".count("a"))   # 2 3
print("-".join(["2024", "05", "17"]))  # 2024-05-17

Escape characters and raw strings

A backslash (\) combines with the next character to mean something special: \n is a new line, \t a tab and \' a quote. That is why printing the Windows path "C:\new\table" mangles it, as \n and \t turn into a line break and a tab. A raw string, written with an r in front as in r"C:\new\table", keeps every backslash as a literal character, which is why raw strings are used for file paths and regular expressions.

In real projects

Where this shows up in real projects

Cleaning user input before storing it is the main job of string methods. An email address is normalised with email.strip().lower() before the database lookup, so "Aye@Mail.com " and "aye@mail.com" refer to the same user. Blogs turn a title into a URL slug with lower() and replace(" ", "-").

Log files and CSV lines are broken into fields with line.split(","). Slicing is how you show only the last four digits of a phone or card number while masking the rest with *, and how you pull the extension off a file name. Messages, email templates and nearly every log line are built with f-strings. Search boxes rely on the in operator or find() to check whether what the user typed appears in a product name.

Common mistakes

Common mistakes

1. Not storing a method's result

A bare name.upper() line creates a new string and immediately throws it away. Assign it back with name = name.upper(). The mistake usually comes from expecting strings to behave like lists, whose methods such as append() change the object in place.

2. Thinking the slice stop is included

"Python"[1:3] is "yt", not "yth". When you want n characters, think text[start:start + n] to avoid off-by-one errors. A quick sanity check is that the slice length always equals stop minus start.

3. Joining a string and a number with +

"Age: " + 25 raises TypeError: can only concatenate str (not "int") to str. Using f"Age: {age}" avoids the error entirely, because the f-string does the conversion.

Best practices

Best practices

  • Make f-strings your default for putting values into text.
  • Apply strip() and lower() (or casefold()) to user input before comparing it.
  • When debugging, print(repr(text)) to reveal invisible spaces and \n characters.

Mini challenge

Mini challenge: user profile text helpers

Write three functions that clean up the name and phone number from a sign-up form and generate a username.

  • clean_name(raw) removes extra spaces and capitalises every word (" aung ko ko " → "Aung Ko Ko")
  • make_username(full_name) joins the lowercase words with _ ("aung_ko_ko")
  • mask_phone(phone) shows only the last 4 digits and hides the rest with *
  • Print a check showing the original raw string is unchanged
profile.py
def clean_name(raw: str) -> str:
    # TODO: split on whitespace, join with one space, then .title()
    ...


def make_username(full_name: str) -> str:
    # TODO: lowercase the words and join them with "_"
    ...


def mask_phone(phone: str) -> str:
    # TODO: "*" repeated (len - 4) times + the last 4 characters
    ...


raw = "   aung   ko ko  "
# TODO: print the cleaned name in quotes, the username and the first name
# TODO: print mask_phone("09123456789")
# TODO: print whether the name starts with "Aung" and that raw is unchanged

Expected: The program prints: Name: 'Aung Ko Ko' Username: aung_ko_ko First name: Aung Phone: *******6789 Starts with 'Aung': True ' aung ko ko ' unchanged: True

Show hint

" ".join(raw.split()) collapses repeated spaces into one. "*" * 7 gives "*******", and phone[-4:] is the last four characters.

Show solution
profile.py
def clean_name(raw: str) -> str:
    """Remove extra spaces and capitalise each word."""
    return " ".join(raw.split()).title()


def make_username(full_name: str) -> str:
    """'Aung Ko Ko' -> 'aung_ko_ko'"""
    return "_".join(full_name.lower().split())


def mask_phone(phone: str) -> str:
    """Keep only the last 4 digits visible."""
    return "*" * (len(phone) - 4) + phone[-4:]


raw = "   aung   ko ko  "
name = clean_name(raw)
print(f"Name: '{name}'")
print(f"Username: {make_username(name)}")
print(f"First name: {name.split()[0]}")
print(f"Phone: {mask_phone('09123456789')}")
print(f"Starts with 'Aung': {name.startswith('Aung')}")
print(f"'{raw}' unchanged: {raw == '   aung   ko ko  '}")

Quick quiz 1 / 3

With word = "Mandalay", what does print(word[1:4], word[-3:]) output?

Quick quiz 2 / 3

After s = " hi " and a bare call s.strip(), what does print(len(s)) show?

Quick quiz 3 / 3

Which of these lines raises an error?

What to remember

  • A string is a sequence of characters indexed from 0, with -1 as the last one.
  • A slice [start:stop] excludes stop; a single index past the end raises IndexError.
  • Strings are immutable, so every method returns a new string you must store.
  • Use f-strings to put values into text, and len() and in to inspect it.

The Python Tutorial — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.