basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    Chapter 4PythonBasics

    Strings in Python: slices, methods and f-strings

    A string is text in quotes, a row of characters numbered from zero. A slice takes a piece by position, methods search, change case and trim spaces, and an f-string builds text out of values. Pull the shooting date and the extension out of the photo name IMG_20261021_183045.jpg — and find out why the path D:\new prints with a line break.

    New hereString methodsSlices: [:n]f-strings

    What you’ll get

    A phone names photos by the date and time they were taken. Pull the date out of the name in the familiar form, plus the extension:

    # photo_date.py
    name = "IMG_20261021_183045.jpg"
    year = name[4:8]
    month = name[8:10]
    day = name[10:12]
    dot = name.rfind(".")
    ext = name[dot + 1:]
    print(f"{year}-{month}-{day}, extension {ext}")
    python photo_date.py
    # 2026-10-21, extension jpg

    name[4:8] is characters 4 through 7: 2026. rfind(".") finds the last dot, and everything after it is the extension. f"…" substitutes values into the braces.

    What will it print?
    name = "photo.JPG"
    name.lower()
    print(name)
    What will it print?
    Answer:
    photo.JPG

    String methods don’t change the string; they return a new one. name.lower() returned photo.jpg, but the result wasn’t saved — name stayed the same. name = name.lower() works.

    How it works: a row of numbered characters

    Every character has a position — an index — starting from zero. A negative index counts from the end: -1 is the last.

     I   M   G   _   2   0   2   6   1   0   2   1  ...  .   j   p   g
     0   1   2   3   4   5   6   7   8   9  10  11       19  20  21  22
                                                        -4  -3  -2  -1

    len(name) is the length, 23 characters. A character is a letter, not a byte: len("naïve") is 5. A string can’t be changed after it’s created: name[0] = "i" is an error. A slice, a method, an f-string all give a new string and leave the old one alone.

    A slice — a piece of a string

    The slice [start:end] takes characters from position “start” up to “end”, not including it. A missing start means from the beginning, a missing end to the end.

    Slice Result What
    name[:3] 'IMG' the first three
    name[4:12] '20261021' positions 4 through 11
    name[-3:] 'jpg' the last three
    name[dot + 1:] 'jpg' from the dot to the end
    name[::-1] 'gpj.540381_12016202_GMI' reversed: the third number is the step

    A slice doesn’t error past the end: "photo"[3:100] is 'to'. An index past the end does: "photo"[10] is an IndexError.

    Methods: search, change, trim

    A method is a function that belongs to a value: write it after a dot, name.upper(). The most common:

    Method Example Result
    strip() " ubuntu \n".strip() 'ubuntu' — no spaces or line breaks at the edges
    lower(), upper() "ERROR".lower() 'error'
    replace(old, new) "a,b".replace(",", ";") 'a;b'
    startswith, endswith "report.pdf".endswith(".pdf") True
    find, rfind "web1".find("b") 2; not found — -1
    count "a-b-c".count("-") 2
    isdigit() "100".isdigit() True; "4.7".isdigit() is False

    Whether a piece is in a string: in — "error" in "disk error on sda" is True. + joins strings and * repeats them: "-" * 20 is a line of 20 hyphens. Cutting a string into parts, split, and joining it back, join, come in the “Lists and tuples” chapter: the parts go into a list there.

    An f-string: text out of values

    The letter f before the quote, and any expression can go in the braces. After a colon comes the format:

    seconds = 376.0
    print(f"Downloads in {seconds / 60:.1f} min")   # Downloads in 6.3 min

    That’s the calculation from Variables and types — now without the extra digits.

    Format Example Result
    .1f f"{6.2666:.1f}" 6.3 — one digit after the point
    , or _ f"{1234567:,}" 1,234,567 — thousands separators
    .0% f"{0.912:.0%}" 91% — a fraction as a percentage
    >6, <6 f"[{'ok':>6}]" [ ok] — width, aligned right or left
    03 f"{7:03}" 007 — leading zeros
    = f"{size=}" size=23.73046875 — name and value, for debugging

    Quotes and the backslash

    Single and double quotes are equal: 'He said "yes"' and "It's" — use the other kind inside. Three quotes in a row make a multi-line string. A backslash starts a special character: \n is a line break, \t a tab. That’s why a Windows path breaks in a regular string:

    print("D:\new\table")
    # D:
    # ew	able
    print(r"D:\new\table")    # D:\new\table
    print("D:/new/table")     # D:/new/table

    r before the quote makes a raw string, where the backslash is an ordinary character. Windows understands forward slashes in paths too.

    Take it further

    The date from the archive name backup-2026-10-21.tar.gz

    The date comes right after backup- and is 10 characters long. Where it starts, len("backup-") will tell you.

    name = "backup-2026-10-21.tar.gz"
    start = len("backup-")
    print(name[start:start + 10])
    # 2026-10-21
    “Yes”, “yes ” and “YES” are the same answer

    Trim the spaces first, then bring it to one case — and compare.

    answer = input("Delete? ")
    print(answer.strip().lower() == "yes")
    A report line: the name left-aligned in 12 characters, the size right-aligned in 8, one decimal

    Width and alignment go after the colon: <12 and >8.1f.

    name = "photos"
    size_gb = 23.73046875
    print(f"{name:<12}{size_gb:>8.1f} GB")
    # photos          23.7 GB

    If it doesn’t work

    IndexError: string index out of range

    Cause
    A position past the end of the string: "photo" has five characters, and the last is [4].
    Fix
    Take the last character with [-1], and check the length with len(). A slice past the end raises no error: "photo"[3:100] is "to".

    TypeError: 'str' object does not support item assignment

    Cause
    Changing a character in place: name[0] = "P". A string can’t be changed after it’s created.
    Fix
    Build a new string and move the name onto it: name = "P" + name[1:].

    Called name.lower(), and the name didn’t change

    Cause
    A string method returns a new string; the old one stays as it was. The result wasn’t saved anywhere.
    Fix
    Assign the result: name = name.lower().

    The path "D:\new\table" prints with a line break and a tab

    Cause
    In a regular string \n is a line break and \t a tab. For "D:\data" Python 3.12 and newer warns: SyntaxWarning: "\d" is an invalid escape sequence.
    Fix
    Write Windows paths as raw strings — r"D:\new\table" — or with forward slashes: "D:/new/table", which Windows understands.

    It prints {x} instead of the value

    Cause
    The f before the quote is missing: without it, braces are ordinary text.
    Fix
    Add the f: f"{x}".