Victor Jeman - Frontend Architectv3.0
Python Fundamentals13 min

The magic of text: advanced strings

Discover advanced string techniques: indexing, slicing, searching, and multiplication.

What You'll Learn

  • Access individual characters in a string using indices
  • Extract portions of strings using slicing
  • Search for substrings with the find() method
  • Multiply and combine strings in creative ways

Think about what happens when you create an account on Instagram, TikTok, or Discord. 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 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.

Accessing characters (indexing)

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:

Negative indices

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:

Slicing

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:

String concatenation

Concatenation means gluing two or more strings together using the + operator. We have used it in previous lessons, but now we will apply it in more interesting contexts.

Let's say you want to build a social media handle from a first name and a hobby:

You can build dynamic messages by combining variables with fixed text:

One important thing to remember: you can only concatenate strings with strings. If you have a number, you must convert it to a string with str():

String multiplication

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:

The find() method

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.

This means that the text "Gamer" starts at position 15 in the string. Let's also 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 a username contains spaces (which is usually not allowed):

Or you can check whether a bio contains a specific hashtag:

The break statement

This is not directly related to strings, but you will use it all the time alongside them. The break statement lets you forcefully stop a while or for loop before it finishes naturally.

Imagine you are writing a program that asks the user to guess a username. You want the loop to stop as soon as they guess correctly:

Without break, the while True loop would run forever. With break, the program exits the loop at the exact moment the condition is met.

Another practical example: you ask the user to enter usernames until they type "stop":

Combine break with find() and you get a powerful tool. For example, you search through multiple usernames until you find one that contains a specific word:

Strings in Python are indexed starting from 0. You can access individual characters with square brackets, extract portions with slicing [start:stop], search for text with find(), and combine or multiply strings with + and *. The break statement stops a loop before it finishes naturally. These techniques are fundamental for any program that works with text.

Exercise : Decoding a reversed spell

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.

Exercise : Riddle room

The 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".

Exercise : Creating a new spell

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.

Exercise : Secret message from ruins

The 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.

Exercise : Username validator

Ask 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!".

Exercise : Simple cipher (letter shift)

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").

Complete game code: Python Kingdom (Lesson 6)

Your game now has a puzzle room! The hero must decode spells and solve riddles:

Test Your Knowledge

Check how well you understood the lesson with these 5 questions.

Question 1 of 5

What does "Python"[0] return?