Beginner·7 min·basics · strings
Strings
You’ll be able to
- Manipulate strings with methods like
.upper(),.split(),.join() - Slice strings by index and by range
- Format text using f-strings and
.format() - Escape special characters and handle multi-line strings
Why this matters
Half of any real Python job is string wrangling: cleaning CSV headers, parsing logs, formatting API responses. f-strings, .strip(), and .split() show up more in production code than any fancy algorithm.
Common pitfalls
- Mutating a string in place. Strings are immutable;
s.replace('a','b')returns a new string, so reassign it. - Using
+in a loop to build strings. It is O(n squared); use''.join(parts)instead. - Forgetting
.strip()on user input or file lines. Trailing\nbreaks comparisons likeline == 'yes'.
Strings are immutable sequences of characters. Index with s[i], slice with s[a:b].
Slice syntax
s[start:stop:step] — any of the three can be omitted. s[::-1] reverses.
Common methods
.upper(),.lower(),.title().strip()— trim whitespace.replace(old, new).split(sep)andsep.join(list).startswith(),.endswith(),.find()
f-string formatting
f"{value:.2f}" — 2 decimal places. f"{n:>5}" — right-align in 5 chars.
Try it
- Take
" hello "and produce"Hello". - Reverse just the first word of
"python rocks".
Practice
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
Progress0 / 3
- Exercise 1
The variable
greetingholds"hello, python". Print it fully uppercased. - Exercise 2
From the variable
sentence = "the quick brown fox", print just the middle two words:quick brown. - Exercise 3
Take
email = "nitesh@nexlev.in"and print the domain part (everything after the@).