Python Strings Tutorial

Cats aren’t the only ones that can have fun with strings! The string data type is extremely important in code because written words are extremely important in our lives. 

In this lesson, we’ll see how we can work with strings in special and powerful ways.

Python Strings 1

Run the example:

Python Strings Tutorial Image 7

Here, we make a (fairly rude) sentence and print it out.

We can access one character, or letter, in that string the same way we access one item in a list.

Change and run:

sentence = "Get off my lawn!"
print(sentence[0])

This code gets the first letter of our sentence.

Python Strings 2

Change and run:

sentence = "Get off my lawn!"
print(sentence[0:3])

This code takes a part of that string, from the first character to the third character, and prints it out.

Change and run:

sentence = "Get off my lawn!"
for character in sentence:
print(character)

This code loops through each character in our sentence and prints it out.

In computer science, a single character is a type of data called a char, not a string.

Python Strings 3

Activity:

Let’s make an anagram generator like so:

import random
word = "tortoise"
anagram = []
for char in word:
anagram.append(char)
random.shuffle(anagram)
print(anagram)
while True:
guess = input("Unscramble the word: ")
if guess == word:
print("Correct!")
break
else:
print("Incorrect.")

Python Strings 4

Explanation:

Set word to the word you want to scramble. In the example code, we scramble the word “tortoise.”

The for loop puts every character of the word into the empty list called anagram.

Then, we use a function called shuffle to scramble the letters.

After the letters are scrambled, we print them out.

The while loop asks the second player to guess the word.

If what player 2 types in matches the word that player 1 put in the code, a message is printed and the loop ends. Otherwise, a different message is printed and the loop keeps going.

Python Strings 5

Hide your code from player 2 like this:

Hide your code from player 2 like this:

  • Make a new file with the + button.

Python Strings Tutorial Image 8

  • Switch to the new file.

Python Strings Tutorial Image 9