Working with Text (Strings)
Read, cut, clean, and join text like a pro
- pick a single letter with indexing and a piece with slicing,
- tidy text with
.upper(),.lower(), and.strip(), - join text with concatenation (
+), - build clean sentences with f-strings.
1. What is a string?
A string is text wrapped in quotes. You can use single quotes '...' or double quotes "..." — both work the same. The quotes tell Python "this is text, not a number or a command".
name = "Python"
print(name)
print(len(name))Output:
Python
6
len(name) counts the characters in the string. "Python" has 6 letters, so it prints 6. Spaces count too!
2. Indexing: picking one letter
Every letter in a string has a position number called an index. Here is the key surprise: counting starts at 0, not 1. You can also count backwards from the end with negative numbers, where -1 is the last letter.
Put the index in square brackets right after the string:
word = "PYTHON"
print(word[0]) # first letter
print(word[2]) # third letter
print(word[-1]) # last letterOutput:
P
T
N
So word[0] is P, word[2] is T, and word[-1] is the last letter N.