Victor Jeman Academy
Python Fundamentals12 min

The string toolbox: case, cleaning, searching

Transform, clean, and search strings with the built-in methods: upper, lower, strip, replace, find, and in.

What You'll Learn

  • Transform case with upper() and lower()
  • Clean whitespace with strip() and replace text with replace()
  • Multiply strings to stamp out patterns
  • Search for substrings with find() and the in operator
  • Combine break with string checks inside a loop

In this lesson

  • Change case with .upper() and .lower(), then compare text without capitalization getting in the way.
  • Clean stray spaces with .strip() and swap text with .replace(old, new).
  • Repeat a string with * to draw borders and bars.
  • Search inside a string with .find() and the in operator, and stop a loop the moment a check passes.

Last lesson you learned to reach into a string by position: one character with [i], a chunk with [start:stop], every other one with a step. Position is only half the job. Now you clean, transform, and search the text itself.

Back in the puzzle room of the Python Kingdom, the encrypted spells need more than slicing. You trim the stray spaces off a scroll, lowercase it so capitalization stops mattering, search it for a word, and stamp out borders to frame the result. These are the named methods every string carries: a small toolbox you reach into all day.

In "Building strings" you assembled text from scratch with + and f-strings. This lesson is the other direction: reshaping strings you already have, cutting, cleaning, and searching them.

Uppercase and lowercase (upper / lower)

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

Two methods flip a string's case: .upper() and .lower(). Each one hands you back a new string and leaves the original alone.

You'll use this most when comparing text and you don't want capitalization to matter. A user who types "Python", "PYTHON", or "python" means the same thing all three times, so lower everything first, then compare:

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 someone types into input(), they tend to fat-finger a space at the start or end. strip() trims the spaces off the beginning and end of a string and leaves the ones in the middle alone.

In practice, strip almost every input() before you use it. It costs nothing and saves you from a space you can't see:

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 finds every occurrence of one piece of text and swaps it for another. Two arguments: what to look for, what to put in its place.

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"

Multiply a string by a whole number and Python repeats it that many times. "-" times 30 gives you a divider line, no typing out 30 dashes by hand. It looks strange the first time, then you realize how much terminal art it saves you.

This is how you draw borders, bars, and dividers without counting characters. It also does real work, not just decoration. A star rating is filled stars next to empty dots, each built by multiplying:

Or a quick decorative frame around 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

Sooner or later you need to search inside a string. The find() method takes a substring (a smaller piece of text), looks for it in the bigger string, and hands back the position where it first shows up. If the substring isn't there, you get -1.

"Coder" starts at position 8. Now search for something that isn't in the string:

That -1 is your "not found" signal, and it's exactly what you check against. You can ask whether a bio contains a particular 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

find() works, but checking != -1 every time gets old. When all you want is a yes/no answer, the in operator is clearer: it gives you True or False straight away, no -1 to compare against.

Drop in straight into an if and the condition almost reads like English:

break combined with strings

You met break back in the while-loops lesson: it stops a loop early. Pair it with find(), in, and lower(), and you can break out the moment a string check passes.

Take a guessing game. You ask for a username, compare it to the right answer, and break the loop the instant they get it:

Or collect usernames one at a time and stop when they type "stop", building up the list with concatenation as you go:

And break plus find() lets you scan a series of usernames and stop at the first one that contains a word you care about:

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 : 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 : 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 in), (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)

Optional deep-dive: skip this one if you just want the basics. It is a fun challenge, not a building block for later lessons.

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

Your game now has a puzzle room. The hero decodes spells and solves riddles to get through:

You wrote the same shape over and over today: set a counter to 0, loop while it's under the length, do something, add 1. That works, but it's a lot of bookkeeping for "visit every character." Next lesson you meet the for loop, which walks a string (and soon a list) one item at a time with none of the counter juggling. And the slicing you learned carries straight over to lists.

Test Your Knowledge

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

Question 1 of 4

What does the find() method do?