How Python handles text, formatting, slicing, and useful string operations
Strings represent text in Python. They are created using quotes:
message = "Hello, world!"
name = 'Alice'
You can combine strings using the + operator:
first = "Hello"
second = "Python"
result = first + " " + second
print(result) # Hello Python
Use len() to get the number of characters:
text = "Python"
print(len(text)) # 6
Strings behave like sequences, so you can access characters by index:
word = "Python"
print(word[0]) # P
print(word[-1]) # n
Slicing extracts parts of a string:
print(word[0:3]) # Pyt
print(word[2:]) # thon
print(word[:4]) # Pyth
Python includes many built‑in string methods:
text = " hello world "
print(text.upper()) # HELLO WORLD
print(text.lower()) # hello world
print(text.strip()) # hello world
print(text.replace("world", "Python")) # hello Python
sentence = "Python is awesome"
print(sentence.find("is")) # 7
print(sentence.find("Java")) # -1 (not found)
Python offers several ways to format strings.
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
print("My name is {} and I am {} years old.".format(name, age))
Use triple quotes for multi-line text:
message = """This is
a multi-line
string."""
Now that you understand how to work with strings, you’re ready to explore Python’s core data structures in Lesson 5: Lists, Tuples, and Dictionaries.
← Back to Lesson Index