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
| Method | What it does | Example 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 beginning | gives 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
- Count how many vowels are in your name.
- Turn "ram shrestha" into "Ram Shrestha" (look up
title()). - Check whether an email address contains an @ sign.
Next lesson: grouping code into reusable functions.

Comments
Loading comments…