Strings in Python
A string is a sequence of characters. You can read single characters by position, take slices, and call methods that return changed copies.
What is Strings?
A string is a sequence of characters. You can read single characters by position, take slices, and call methods that return changed copies.
Work with text in Python: length, indexing, slicing and string methods.
When should you use it?
- Learn Python syntax through a practical example.
- Build a foundation for larger programming problems.
- Test an idea quickly without a local setup.
Example code
text = "Python is fun"
print(len(text)) # number of characters
print(text[0], text[-1]) # first and last character
print(text[0:6]) # slicing: characters 0 to 5
print(text.upper())
print(text.lower())
print(text.replace("fun", "powerful"))
print(text.split()) # split on spaces into a list
print("is" in text) # check for a substring
# Strings are immutable: methods return a new string.
name = " ada lovelace "
clean = name.strip().title()
print(clean)
# Join a list of strings with a separator.
print("-".join(["2026", "11", "01"]))
Expected output
13
P n
Python
PYTHON IS FUN
python is fun
Python is powerful
['Python', 'is', 'fun']
True
Ada Lovelace
2026-11-01
How it works
Indexes start at 0 and negative indexes count from the end. Slices such as text[0:6] stop before the end index, and methods like strip(), title() and replace() return new strings because strings never change in place.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Count Uppercase Letters Count the capital letters in a text. Easy
- Initials From a Name Build uppercase initials from a full name. Easy
- Replace Spaces With Dashes Turn spaces into dashes to make a URL-style slug. Easy