Working with text in Python

A Python string is an object with methods, and almost every method hands back a new string rather than changing the one you called it on. This set covers indexing from either end, splitting a line into fields and joining it back, slicing a value by position, and cleaning a messy field before you compare it. The task runs one line that does all four jobs and asks you to read what it printed.

4 questions 1 task Read the lesson

Questions

Each one is marked as you go, and the explanation arrives straight after, which is the part worth reading.

4 questions, marked as you go.

1 For the string word, what does word[-1] give you?
2 line holds "Admin:user". The code runs line.lower() and then prints line. What appears?
3 How do you join a list of parts back into one string with hyphens between them?
4 code holds "INV-2026-0042". What does code[4:8] give you?

Tasks

These need your own device. Run the command in Termux, then paste what it printed. The marking looks at what the output means, so spacing, version numbers and ordering do not matter. If you have not installed anything yet, the lesson covers the setup.

Split, join, slice and clean a field

This splits a line from a passwd-style file into fields and picks two of them out, joins a list of words back together with hyphens, slices a prefix, a year and a suffix out of an ID, and cleans a messy field by stripping the spaces and folding it to lower case. Paste all four lines.

Run this in Termux On your own device. Nothing on this page executes it. The command runs in your terminal, and this box only reads what you paste back.

python3 -c "line = 'root:x:0:0:root:/root:/bin/sh'; fields = line.split(':'); print(fields[0], fields[2], len(fields)); print('-'.join(['one','two','three'])); code = 'INV-2026-0042'; print(code[:3], code[4:8], code[-4:]); raw = ' Admin '; print(raw.strip().lower())"
Marking your own work Both halves of this are checked in your browser, with no server involved, so nothing stops you from pasting output you did not run. The tasks are written so that the easiest way to pass one is to actually do it and read the result, which is the whole intention.

All sets Read the lesson