Step 1 of 8 · Reading · ~3 min
Learn
Working with Text
String Operations
Text is the data you meet first and use most: input lines, names, file paths, log records. This lesson covers the operations that work on any string - measuring it, pulling characters and substrings out of it, gluing pieces together, and searching inside it.
A string is an indexed sequence
Every character sits at a numbered position. Counting starts at 0, and negative numbers count back from the end:
b a n a n a
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
len() gives the number of characters:
The highest valid index is len(s) - 1, never len(s).
Slicing pulls out a substring
s[start:stop] gives the characters from start up to but NOT including stop.
Two traps worth memorising:
stamp[0:4]is four characters (0, 1, 2, 3), not five. The stop is excluded.- Out-of-range SLICE bounds do not raise; Python clamps them.
"abc"[1:99]is"bc", and"abc"[7:9]is the empty string. Out-of-range INDEXING does raise. Slices forgive, indexes do not.
A slice takes an optional third part, the step:
Joining and repeating
+ joins a string to a string only: "total: " + 5 is a TypeError, so convert with str(5) or use an f-string. * needs a whole number on the other side.
Strings cannot be edited in place
Strings are immutable. To "change" one you build a new string out of pieces and reassign it:
Slice off the part you keep, concatenate the part you want: that is how every string edit is done.
Searching and walking
in answers a yes/no question, and a for loop visits one character at a time:
Common mistakes
- Using
len(s)as an index.s[len(s)]raises IndexError; the final character iss[len(s) - 1], or simplys[-1]. - Slicing to the end when you meant "everything except the two outer characters". Stopping at
len(s)keeps the final character, so a five-character word comes back six characters long once you add an end onto it. - Forgetting the one-character case. In
"a", index0and index-1are the SAME character, so code that grabs both ends sees it twice and printsaainstead ofa. - Assigning to
s[0]. That raises TypeError rather than editing the string.
Your exercise
Swap the two ends of the input string and leave everything between them exactly where it is. The starter already reads the line and prints a value, so the work is building the right string first. A string of length 0 or 1 has no two ends to swap, so print it unchanged, and handle that case before you go anywhere near index -1.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…