LearnPy Hub
BasicsBeginnerLesson 6 of 32

Strings

Watch the ideaA string is a row of characters
s = "Python"
s
P0
y1
t2
h3
o4
n5

Each character has a position, called its index. Counting starts at 0.

1Level 1 · BasicsBasics

A string is a piece of text: a name, a sentence, even a whole book. Strings are everywhere in programs, so Python gives you lots of tools to work with them.

Creating strings

Use single or double quotes. Triple quotes ("""...""") let a string span several lines. To put a quote inside, use the other kind: "It's fine".

Indexing: one character at a time

Each character has a position called an index, and counting starts at 0:

 P  y  t  h  o  n
 0  1  2  3  4  5
-6 -5 -4 -3 -2 -1

s[0] is "P". Negative indexes count from the end, so s[-1] is the last character, "n". len(s) gives the length (6).

Slicing: a piece of a string

s[start:stop] takes characters from start up to but not including stop:

s = "Python"
s[0:3]    # "Pyt"
s[2:]     # "thon"   (to the end)
s[:2]     # "Py"     (from the start)
s[::-1]   # "nohtyP" (step -1 reverses)

Useful string methods

MethodWhat it does
s.upper(), s.lower(), s.title()change case
s.strip()remove spaces from both ends
s.replace("a", "b")replace text
s.split()split into a list of words
" ".join(words)join a list back into one string
s.find("x"), s.count("x")position of / number of occurrences
s.startswith("x"), s.isdigit()yes/no checks

Strings can't be changed

Strings are immutable: methods like upper() return a new string and leave the original alone. To keep the result, store it: name = name.upper().

Checking and looping

"py" in "python" is True. A for loop visits each character: for ch in s:. You'll meet loops properly two lessons from now.

Key points: indexes start at 0 and negative ones count from the end; slices stop before the stop index; methods return new strings; use in to search.

See it in actionIndexing and slicing a string

See how positions start at 0 and how methods build new strings.

Step-by-step

Try it yourselfExample 1: Indexing and slicing

Try other numbers in the brackets. What happens with s[10]?

example_1.py
Output appears here
Fill in the blanks

First and last

Fill the blanks so the program prints the first letter and the last letter of Python: P n.

blanks.py
word = "Python"
print(word[], word[])
Fix the bug

Changing one letter

This should turn cat into bat and print it, but it crashes. Fix it.

buggy.py

Example 2: Cleaning up text

Methods return new strings, so we can chain them one after another.

example_2.py
Output appears here
Fill in the blanks

Clean up a name

Fill the blanks so " rIMa " becomes Rima: remove the spaces, then fix the capitals.

blanks.py
name = "  rIMa  "
print(name.().())

Example 3: Split and join

split() cuts a sentence into separate words (the square brackets show them as a list, which you'll meet in the Lists lesson); join() glues the words back together.

example_3.py
Output appears here
Your turn

Initials

Read a full name like Sadia Rahman Khan and print the initials in capitals: SRK.

Example inputSadia Rahman KhanExpected outputSRK

my_code.py

Example 4: Searching in a string

in, find() and count() answer "is it there?", "where?" and "how many?".

example_4.py
Output appears here
Your turn

Count the vowels

Read a word and print how many vowels (a, e, i, o, u) it has, ignoring capitals. Banana gives 3.

Example inputBananaExpected output3

my_code.py

2Level 2 · IntermediateSlicing tricks and text processing

Steps and negative steps

s[::2] takes every second character; s[::-1] reverses the string. A palindrome check is just s == s[::-1].

Counting and replacing

s.count("a"), s.replace("old", "new"), s.startswith("Dr."), s.endswith(".py"), s.isdigit(), s.isalpha() answer most everyday questions.

Finding text

s.find("x") gives the position of the first match, or -1 when there is none. "x" in s just answers yes or no.

Characters are numbers

ord("A") is 65 and chr(66) is "B". That's how a Caesar cipher shifts letters.

See it in actionReversing and checking a palindrome

Watch the cleaned text and its reverse appear, then the comparison.

Step-by-step

Example 5: Shifting a letter, Caesar style

Change letter to "Y" and see it wrap around to the start of the alphabet. In the Loops lesson you'll shift every letter of a whole message.

example_5.py
Output appears here

Example 6: Text statistics

Paste your own sentence into text.

example_6.py
Output appears here

3Level 3 · AdvancedUnicode, encoding and advanced formatting

Strings are Unicode

A Python string holds characters, not bytes, so Bangla works naturally: len("বাংলা") counts code points. Some letters are built from several code points (a consonant plus a vowel sign), so the count can be larger than what you see.

Bytes and encodings

s.encode("utf-8") turns text into bytes for files and networks; b.decode("utf-8") goes back. English letters take 1 byte, Bangla letters 3.

str.translate and str.maketrans

Replace many characters in one pass, for example English digits to Bangla digits.

Templates and nested format specs

Widths can come from variables: f"{name:<{width}}". f"{value=}" prints both the expression and its value, which is great for debugging.

Example 7: Bangla text, bytes and digits

translate() changes every digit in one pass.

example_7.py
Output appears here

Example 8: Dynamic widths and self-documenting f-strings

The table widens to fit the longest name automatically.

example_8.py
Output appears here
Common mistakes[0] = "J" raises a TypeError because strings can't be changed in place. Build a new one instead: s = "J" + s[1:].
Exercise · predict the output

What does this print?

s = "programming"
print(s[3:7])
Quick quiz · 5 questions
1. What is "abc"[::-1]?
2. Which method splits a sentence into words?
3. What is the index of the first character in a string?
4. After name = "ali" and name.upper(), what is name?
5. What does len("hello world") return?
Ready to practice strings?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Strings · LearnPy Hub