String tools
Section 9: Strings in depthLesson 9.1 · ⏱ 9 min
A string in Python has ready tools. We write the variable's name, then a dot, then the tool's name.
upper()makes the letters capital, andlower()makes them small.len(name)counts the letters (a space is a letter too).name[0]is the first letter, because counting starts from zero.name[0:4]is a piece from letter 0 up to just before letter 4.replaceswaps one word for another, andsplit()splits the sentence into a list of words.
name = "Robo Egypt"
print(name.upper())
print(name.lower())
print(len(name))
print(name[0])
print(name[0:4])
print(name.replace("Egypt", "Lab"))
words = "I love Python".split()
print(words)
print(len(words))
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗ROBO EGYPT robo egypt 10 R Robo Robo Lab ['I', 'love', 'Python'] 3

📌 Another example: counting the vowels
We go through every letter, and count a, e, i, o and u.
word = "programming"
count = 0
for ch in word:
if ch in "aeiou":
count = count + 1
print(word, "has", count, "vowels")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗programming has 3 vowels
Test yourself
- Print your name in capital letters, then its number of letters.
- Write a sentence of five words, split it with split, and print the last word.
✍️ Practise
Change the name in the example to your name, and predict the result before you click Run.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
Print the word backwards ([::-1]).
👀 Show the solution🙈 Hide the solution
print("robot"[::-1])
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗tobor
Result: tobor
Medium
Does the word read the same both ways (a palindrome)?
👀 Show the solution🙈 Hide the solution
When the program asks, we type: level.
word = input("Word: ")
if word == word[::-1]:
print("palindrome")
else:
print("not palindrome")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Word: level palindrome
Result: level: palindrome
Hard
Make the first letter of every word a capital (without title).
👀 Show the solution🙈 Hide the solution
text = "robo egypt lab"
words = text.split()
out = []
for w in words:
out.append(w[0].upper() + w[1:])
print(" ".join(out))
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Robo Egypt Lab
Result: Robo Egypt Lab

