← All lessons

Lesson 3 of 18 · about 14 minutes

Working with Strings 🧵

Text values are called strings. Python gives you a huge toolkit for slicing, joining and transforming them.

f-strings: the best way to build text

name = "Grace"
print(f"Hello {name}, you have {3 * 4} messages")

Useful methods

s = "  Python Rocks  "
print(s.strip())        # remove spaces at both ends
print(s.lower())        # "  python rocks  "
print(s.upper())
print("a,b,c".split(","))   # ['a', 'b', 'c']
print("-".join(["x","y"]))  # x-y
print("hello".replace("l","L"))
print(len("hello"))         # 5

Indexing and slicing

word = "Pythonaut"
print(word[0])     # P
print(word[-1])    # t
print(word[0:6])   # Python
print(word[6:])    # aut
print(word[::-1])  # reversed
💡 Strings are immutable. Methods return a new string; the original never changes.

Your challenge

Given word = "racecar", print the word reversed, then print True if it is a palindrome (same backwards) using a comparison, then print the word in capitals.