Course 2.2Lesson 1 of 5
A string is a row of characters inside quotation marks. len() gives the number of characters, including spaces. Every character has a position, and the first position is 0. Square brackets pick one character: word[0] is the first and word[-1] is the last. A position that is too big gives an IndexError. A string cannot be changed in place, so to change one we make a new string and store it in the name.
Try the code and the simulations beside the lesson.
After this lesson you can
You already used text in print("Hello"). In Python, text has a name: a string. A string is a row of characters: letters, digits, spaces and signs, one after the other, inside quotation marks.
The word computer is a row of eight characters. The function len() counts them.
The picture shows both ways. Use whichever is easier. To get the last character, word[-1] is easier than word[len(word) - 1].
It looks strange at first. The reason is that a position tells how far you are from the start. The first character is 0 steps from the start. Almost every programming language does this, so it is worth learning once, well. A good rule: in a string of length n, the positions are 0 to n - 1.
The positive positions run from 0 to 5, and the negative ones from -6 to -1. Both name the same 6 letters.
What if you ask for a position that is not there?
Can you change a letter of a string? Try to change cat to bat.
What do we do instead? We make a new string and store it in the same name.
len("2026") is 4, because "2026" is a string of four characters. len(2026) is an error, because a number has no length. Remember the lesson on types: the quotation marks decide.
word[0].word[len(word)]. The last position is len(word) - 1, or word[-1].word[0] = "b" is an error. Make a new string.len("a b") is 3.len() on a number. len(12) is an error. Use len("12").Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
len() counts them, spaces too.-1 is the last.IndexError.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
len("Hi there"), "Hi there"[0] and "Hi there"[-1]?python have?"cat"[3] give an error?"cat" into "cap"?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.