Python for Beginners: Learn to Code from Zero · Lesson 7 of 10

Lesson 7: Working with Text (Strings)

Slice, search and change text. Learn indexing, slicing and the most useful string methods.

Lesson 7: Working with Text (Strings)

Text in Python is called a string. A string behaves like a list of characters, so you can pick letters by position, starting at 0.

word = "Himalaya"
print(word[0])
print(word[-1])
print(len(word))

Output:

H
a
8

Slicing

text[start:stop] takes the part from start up to (not including) stop.

word = "Himalaya"
print(word[0:4])
print(word[4:])
print(word[::-1])

Output:

Hima
laya
ayalamiH

Useful methods

MethodWhat it doesExample result
upper()capital letters"nepal".upper() gives NEPAL
lower()small letters"NEPAL".lower() gives nepal
strip()removes spaces at both ends" hi ".strip() gives hi
replace(a, b)swap text"a-b".replace("-", " ") gives a b
split()break into a list"a b c".split() gives ['a', 'b', 'c']
startswith(x)check the beginninggives True or False
sentence = "  Learn Python every day  "
clean = sentence.strip()
print(clean.upper())
print(clean.replace("Python", "coding"))
print(clean.split())

Output:

LEARN PYTHON EVERY DAY
Learn coding every day
['Learn', 'Python', 'every', 'day']

Searching

text = "Mount Everest is in Nepal"
print("Everest" in text)
print(text.find("Nepal"))
print(text.count("e"))

Output:

True
20
3

Strings cannot be changed in place. Methods like upper() give you a new string, so store the result in a variable if you want to keep it.

A small example: is it a palindrome?

word = "madam"
if word == word[::-1]:
    print(word, "is a palindrome")
else:
    print(word, "is not a palindrome")

Output:

madam is a palindrome

Try it yourself

  1. Count how many vowels are in your name.
  2. Turn "ram shrestha" into "Ram Shrestha" (look up title()).
  3. Check whether an email address contains an @ sign.

Next lesson: grouping code into reusable functions.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 7: Working with Text (Strings) | MeroSir