Learn to measure strings with len(), and pick out individual characters using index positions. Some code is provided โ you fill in the key parts!
len() to find the number of characters in a stringstring[0] to access individual charactersstring[-1] to access from the endstring[0:3] to extract substringsโฌ๏ธ Yellow numbers = positive index (0 to 5) | Blue numbers = negative index (-6 to -1)
Type start and end values to see what slice you get from "PYTHON". Try different combinations!
input.txt in the same folder as your Python file.
Hello World Python Programming GCSE Computer Science Jersey Channel Islands The cat sat on the mat Edexcel 1CP2 Specification
___ gap. Hints are in the comments. Once you figure it out, type it in IDLE and run it!
# Lesson 2 โ Length and Indexing # Fill in the ___ gaps before running! input_file = open("input.txt", "r") output_file = open("output.txt", "w") for line in input_file: line = line.strip() # Find the length of the line โ how many characters? length = ___(line) # HINT: use len() # Get the first character (index 0) first_char = line[___] # HINT: what's the index of the first item? # Get the last character using negative indexing last_char = line[___] # HINT: -1 gives the last character # Get the first 3 characters using slicing first3 = line[___:___] # HINT: start at 0, stop at 3 print(f"Line: {line}") print(f"Length: {length} | First: {first_char} | Last: {last_char} | First3: {first3}") output_file.write(f"{line} โ {length} chars\n") input_file.close() output_file.close() print("Done!")
This code has 4 bugs. Click on each red underlined section to reveal the fix.
word = "Jersey", what does len(word) return?s = "Python", what is s[0]?s = "GCSE", what is s[1:3]?word = "Code", what does word[-1] return?Look at each code snippet and predict what will be printed. Click to reveal!
word = "Python"
print(len(word))s = "Hello"
print(s[1] + s[4])word = "Computing"
print(word[0:4])name = "Jersey"
print(name[-2])Match each function to its description. Click two cards to flip them!
word[::-1] reverses a string!line[::-1]line[::2] to get every other character. What does line[1::2] do?