Lesson 4 of 6 · Numbers, Strings and Operators · 2 min read · Updated
Strings: working with text
Quotes, special characters, picking out letters and slices — and why a string never changes.
A string (str) is text in quotes. Single and double quotes mean the same thing; pick the one that saves escaping, like "It's ready".
Special characters
print("Line one\nLine two")
print("She said \"hi\"")
print('It\'s fine')
print("C:\\new")
print(r"C:\new")
Line one
Line two
She said "hi"
It's fine
C:\new
C:\new
A backslash starts an escape: \n is a new line, \t a tab, \" a quote, \\ a real backslash. An r before the quotes makes a raw string, where backslashes are just backslashes — handy for Windows paths.
Indexing and slicing
word = "Python"
print(word[0])
print(word[-1])
print(word[0:3])
print(word[2:])
print(word[:2])
print(word[::-1])
print(len(word))
P
n
Pyt
thon
Py
nohtyP
6
- Positions start at 0.
word[-1]counts from the end. word[start:end]takes from start up to, but not including, end — the same rule asrange().- Leave out start or end to mean "from the beginning" or "to the end".
- A third number is the step.
[::-1]walks backwards, reversing the string.
Joining and repeating
first = "Tamil"
print(first + " Nadu")
print("ha" * 3)
print("-" * 20)
Tamil Nadu
hahaha
--------------------
Warning
Strings are immutable: word[0] = "J" raises a TypeError. You never change a string — you build a new one, such as "J" + word[1:], which gives "Jython".
s = "Chennai". What is s[1:4]?
Try this now
- Ask for a word and print its first letter, last letter and length.
- Check whether a word is a palindrome by comparing it with
word[::-1]. Try "malayalam". - Print a box around your name using
"*" * nfor the top and bottom lines.
Create a free account to save your progress, or sign in.