1.4.1 String Manipulation
Video
1.4.1 String Manipulation
In order to complete the Word Ladder Challenge, you are going to learn how to access and manipulate pieces of an entire string in Python. The video below shows some of the common techniques for doing this.
String Indexing
You can access individual characters in a string using square brackets with an index number. Important: Python starts counting at 0!
food = "hamburger" print(food[0]) # Prints 'h' (first character) print(food[3]) # Prints 'b' (fourth character, index 3)
String Slicing
You can get a portion of a string using slicing with a colon:
food = "hamburger" print(food[3:]) # Prints 'burger' (from index 3 to the end) print(food[:3]) # Prints 'ham' (from start to index 3, not including 3) print(food[1:5]) # Prints 'ambu' (from index 1 to 5, not including 5)
String Concatenation
You can combine strings using the + operator:
print("turkey" + food[3:]) # Prints 'turkeyburger'
Important Note
The following code is NOT allowed in Python:
puzzle1 = "dog" puzzle1[0] = "c" # ❌ This will cause an error!
Python will not allow you to change a single letter in a string like this. You must construct a new string using slicing and concatenation, as shown in the video.
Try It Yourself
Start with this example in the editor below to practice string manipulation:
Steps to follow:
- Run the code to see how indexing and slicing work
- Try modifying the code to extract different parts of the string
- Practice combining strings using the
+operator
Note: The video shows creating a file in Spyder, but you're using the browser editor. Just type your code directly in the editor below!
Loading Python environment...