Victor Jeman - Frontend Architectv3.0
Python Fundamentals20 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
  • Measure string length with len()
  • Transform case with upper() and lower()
  • Extract portions of strings using slicing
  • Clean whitespace with strip() and replace text with replace()
  • Search for substrings with find() and the in operator
  • Multiply and combine strings in creative ways

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.

Creare cont — procesare text
PIXEL PORTAL
Creeaza cont nou
pixel_knight
••••••••
Creeaza cont

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)

text = "gamer_alex"
g
0
a
1
m
2
e
3
r
4
_
5
a
6
l
7
e
8
x
9

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:

Avatar: poza vs. initialeapasa pe un profil

Negative indices

text = "tech_wizard"
t
-11
e
-10
c
-9
h
-8
_
-7
w
-6
i
-5
z
-4
a
-3
r
-2
d
-1

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.

String length (len)

len() — lungimea unui stringalege un username
d
a
r
k
_
w
i
z
a
r
d
len("dark_wizard") = 11
perfect

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.

python
username = "dark_wizard"
print(len(username))  # displays: 11

len() 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:

Uppercase and lowercase (upper / lower)

upper() / lower() — majuscule si minuscule
"Shadow Ninja"
text = "Shadow Ninja"

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.

Slicing

text = "shadow_ninja"
s
0
h
1
a
2
d
3
o
4
w
5
_
6
n
7
i
8
n
9
j
10
a
11
text[0:6] = "shadow"

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

Concatenare cu +
@
+
r
a
d
u
+
_
+
g
a
m
i
n
g
"@" + "radu" + "_" + "gaming" = "@radu_gaming"

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:

Cleaning whitespace (strip)

strip() — curata spatiile din jur
input brut (cu spatii)
s
h
a
d
o
w
p
r
o
username = input(...)
curat = username.strip()

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:

Replacing text (replace)

replace() — inlocuieste text
inainte
C
o
o
l
G
a
m
e
r
text = "Cool Gamer"
rezultat = text.replace(" ", "_")

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.

String multiplication

Inmultire cu *
h
a
* 3
"ha" * 3 = "hahaha"

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

text.find()
G
0
a
1
m
2
e
3
r
4
5
|
6
7
C
8
o
9
d
10
e
11
r
12
13
|
14
15
P
16
r
17
o
18

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:

The in operator

operatorul in — exista in string?alege un cuvant
bio
c
o
d
|
p
y
t
h
o
n
|
g
a
m
i
n
g
# operator in
"python" in bio
True
# echivalent cu find()
bio.find("python") != -1
True

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

break combined with strings

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.

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?