Discover advanced string techniques: indexing, slicing, searching, and multiplication.
Think about what happens when you create an account in a game, a school portal, or a coding platform. You pick a username, the platform checks it, formats it, and displays it in various places. Everything related to that text, from checking its length to extracting the first letters for an avatar, is done through string manipulation. The apps and websites you use every day are, at their core, text-processing machines.
In this lesson, you will learn to do exactly those things: access individual letters in a username, slice pieces out of it, search for specific characters, and combine texts. These are techniques every programmer uses constantly. Let's dive in.
Your hero has found an ancient library full of encrypted spells. In this lesson you build the puzzle room of the Python Kingdom. You will use indexing, slicing, and find() to decode spells, solve riddles, and create new spells from text combinations.
A string in Python is like a row of boxes, each containing a single character. And each box has a position number that starts from 0, not from 1. This number is called an index.
Let's say you have a username stored in a variable:
If you want to find the first letter of this username, you use square brackets with index 0:
Each character has its fixed position. The letter g is at position 0, a at position 1, m at position 2, and so on. Spaces, underscores, and any other character all count as a position.
This is extremely useful. For example, many platforms use the first letter of the username as a default avatar. You only need a single line of code:
What do you do when you want to access the last character but you do not know how long the string is? Python has an elegant solution: negative indices. Index -1 means the last character, -2 the second to last, and so on.
Negative indices are very practical. Imagine you want to check whether a username ends with a particular character, for example a digit. Instead of calculating the length, you simply use -1:
The first character is always at index 0. The last character is always at index -1. You do not need to know the string length to access the end.
The len() function tells you how many characters a string has. It is one of the most used functions in Python when working with text.
username = "dark_wizard"
print(len(username)) # displays: 11len() counts absolutely all characters: letters, digits, underscores, spaces. Nothing is ignored.
A practical use case right away: you can check if a username meets a minimum and maximum length required by the platform:
Python lets you transform a string to uppercase or lowercase with two simple methods: .upper() and .lower(). The result is a new string, the original is not modified.
The most common use case is comparison without caring about case. If a user types "Python", "PYTHON", or "python", you want to treat them the same:
len() gives you the total number of characters. upper() and lower() transform text without modifying the original. Use lower() when comparing text so capitalization does not matter.
So far we have extracted one character at a time. But what do you do when you need a larger portion of a string? That is where slicing comes in. The syntax looks like this: string[start:stop], where start is the index where you begin, and stop is the index where you stop, without including it.
In the example above, username[0:6] takes the characters from position 0 to position 5 (six characters in total, position 6 is not included). It is like cutting a slice from a row of letters.
There are also very useful shortcuts. If you omit start, Python begins from 0. If you omit stop, it goes all the way to the end:
Slicing is perfect when you want to extract parts of a username. For example, many platforms display only the first few characters of a name in notifications:
Concatenation means gluing two or more strings together using the + operator:
The + operator works, but it gets hard to read when you have many variables mixed with text. Remember f-strings from the input lesson? They are much clearer:
With f-strings you place variables directly in the text, between {}. You no longer need + or str() for numbers:
When a user types something with input(), they often press space accidentally at the beginning or end. strip() removes only the spaces at the beginning and end of a string. Spaces inside the text remain untouched.
In practice, it is almost always a good idea to apply .strip() on any input() before using the value:
The .replace(old, new) method searches for all occurrences of a text in a string and replaces them with something else. It takes two parameters: what to find and what to replace it with.
You can also use replace() to delete a character: replace it with an empty string "".
strip() cleans spaces only from the beginning and end. replace(old, new) replaces all occurrences, including those in the middle of the text.
In Python, you can "multiply" a string by an integer. The result? The string is repeated that many times. It seems odd at first, but it is very useful.
This is perfect for creating visual elements in the terminal. But it can also be used in more creative contexts. For example, a rating system for a profile:
Or you can create a decorative effect for a bio:
When working with text, you often need to search for something inside a string. The find() method does exactly that: it searches for a substring (a smaller piece of text) inside a larger string and returns the position (index) where it first found it. If it finds nothing, it returns -1.
The text "Coder" starts at position 8 in the string. Let's see what happens when we search for something that does not exist:
The value -1 is the signal that the searched text does not exist in the string. This is incredibly useful for checks. For example, you can verify whether the bio contains a specific word:
Or you can check whether the bio contains a special character:
You have already seen that find() returns -1 when it finds nothing. There is however a clearer way to check if a text exists in a string: the in operator. The result is directly True or False, without comparing to -1.
in is used directly in if conditions, which makes the code much easier to read:
When to use in vs find()? If you just want to know if it exists (yes/no), use in. If you also need the position where it is, use find().
You already know that break stops a loop before it ends. Now that you have find(), in, lower() and the other string methods, you can use break in much more interesting scenarios.
A classic example: you ask the user to guess a username. You compare what they typed with the correct answer and stop the loop when they guess right:
You can collect multiple usernames from the user and stop when they type "stop". Here you combine break with concatenation:
The combination of break + find() is very practical: you search through a series of usernames until you find one that contains a specific word:
Use in when you just want to know if a text exists (yes/no). Use find() when you need the exact position where it is.
In the ancient library, spells are written backwards so they cannot be read by intruders. You found the text: "cigam_erif". Write a program that reverses this string character by character (using a while loop and negative indices or starting from the end) to reveal the original spell. Display both the encrypted text and the decoded spell.
SET encrypted_spell = "cigam_erif"
SET decoded_spell = ""
SET i = length(encrypted_spell) - 1
WHILE i >= 0:
decoded_spell = decoded_spell + encrypted_spell[i]
i = i - 1
DISPLAY "Encrypted: " + encrypted_spell
DISPLAY "Decoded: " + decoded_spellThe hero enters the riddle room. An inscription on the wall reads: "In the heart of the forest hides the golden key". The hero must find the word "key" in the inscription using find(). If the word exists, display the position where it starts and extract with slicing the portion of text from that position to the end. If it does not exist, display "The word was not found".
SET inscription = "In the heart of the forest hides the golden key"
SET search_word = "key"
SET position = inscription.find(search_word)
IF position != -1:
DISPLAY "Found at position: " + position
SET fragment = inscription[position:]
DISPLAY "Fragment: " + fragment
ELSE:
DISPLAY "The word was not found!"The hero finds two scrolls with spells: "fire_storm" and "ice_shield". To create a new spell, you must combine the first half of the first spell with the second half of the second one. Use len() and slicing to extract the correct half from each spell, then concatenate them. Display both original spells and the newly created spell.
SET spell1 = "fire_storm"
SET spell2 = "ice_shield"
SET half1 = spell1[0 : length(spell1) // 2]
SET half2 = spell2[length(spell2) // 2 :]
SET new_spell = half1 + half2
DISPLAY "Spell 1: " + spell1
DISPLAY "Spell 2: " + spell2
DISPLAY "Combined spell: " + new_spellThe hero finds an encrypted message on an ancient wall: "AxBxRxAxCxAxDxAxBxRxA". The real message is made up of every other character (positions 0, 2, 4, 6...). Write a program that extracts the secret message by traversing the string with a while loop and a step of 2. Display the encrypted message and the decoded message.
SET encrypted_message = "AxBxRxAxCxAxDxAxBxRxA"
SET secret_message = ""
SET i = 0
WHILE i < length(encrypted_message):
secret_message = secret_message + encrypted_message[i]
i = i + 2
DISPLAY "Encrypted: " + encrypted_message
DISPLAY "Decoded: " + secret_messageAsk the user to enter a username. Check 3 rules: (1) it must have at least 4 characters, (2) it must not contain spaces (use find()), (3) it must not contain "@". Display a message for each broken rule. If all rules are met, display "Valid username!".
READ username from user
SET valid = True
IF length(username) < 4:
DISPLAY "Too short! Minimum 4 characters."
valid = False
IF username.find(" ") != -1:
DISPLAY "Cannot contain spaces!"
valid = False
IF username.find("@") != -1:
DISPLAY "Cannot contain @!"
valid = False
IF valid:
DISPLAY "Valid username!"Write a program that encrypts a message by shifting each letter one position in the alphabet (a->b, b->c, ..., z->a). Create a string with the alphabet: "abcdefghijklmnopqrstuvwxyz". For each character in the message, find it in the alphabet with find(), take the next character (or wrap back to 'a' if it is 'z'), and build the encrypted message. Test with the message "hello" (result: "ifmmp").
SET alphabet = "abcdefghijklmnopqrstuvwxyz"
SET message = "hello"
SET encrypted_message = ""
SET i = 0
WHILE i < length(message):
SET character = message[i]
SET position = alphabet.find(character)
IF position != -1:
SET new_position = (position + 1) % 26
encrypted_message = encrypted_message + alphabet[new_position]
ELSE:
encrypted_message = encrypted_message + character
i = i + 1
DISPLAY "Original: " + message
DISPLAY "Encrypted: " + encrypted_messageYour game now has a puzzle room! The hero must decode spells and solve riddles:
Check how well you understood the lesson with these 5 questions.