It’s hard to imagine an application without text. And to use text, we need strings. Strings are not less important in Python than numbers, so let’s explore them in detail. Let’s start with quotes – this is what we need to define strings.
Table of Contents
Quotes
We can use single, double or triple quotes for string literals. We use single quotes if we need double quotes inside the string:
- >>> print('He said: "Help me!"')
He said: "Help me!"
We use double quotes if we need single quotes or apostrophes inside the string:
>>> print("Jannet's car")
Jannet's car
We can also use quotes inside quotes but then they must be escaped with a backslash:
>>> text = 'I don\'t like Mike\'s dog.'
>>> text
"I don't like Mike's dog."
We use triple quotes if the string must span more than one line. These may be triple double quotes:
>>> text = """
... This is a longer string
... that spans several lines.
... That's why we are using
... triple quotes.
... """
>>> print(text)
This is a longer string
that spans several lines.
That's why we are using
triple quotes.
Indexing Strings
Strings can be indexed in both directions. We use 0-based indexes in the forward direction and -1-based indexes in the backward direction:

We can print a particular character from the string by using its index in square brackets:
>>> text = "This is a text."
>>> print(text[0]) # print the first (at index 0) character
T
>>> print(text[14]) # print the 15th character, which is a period.
.
If we need the last element of a string, it’s easier to use the -1 index:
>>> text[-1]
'.'
We can use other negative indices:
>>> text[-2]
't'
>>> text[-3]
'x'
Comparing Strings
We can use all the comparison operators to compare strings. Strings consist of Unicode characters and each character in Unicode is represented by a number and these numbers are compared. It means, the order is not strictly alphabetical, because all capital letters come before small letters in Unicode.
We have the following comparison operators:

Some examples:
>>> "hello" == "hello"
True
These should be not equal:
>>> a = "hello"
>>> b = "hi"
>>> a != b
True
The first character to differ is the second one. ‘i
’ comes after ‘e
’:
>>> "hi" > "hello"
True
Capital ‘Y
’ comes before small ‘y
’:
>>> "Yes" < "yes"
True
We can confirm this by means of the ord
function, which gives us the Unicode number of the character:
>>> ord("Y"), ord("y")
(89, 121)
Membership
We can check if a particular element is contained or not in the string. We use the membership operators in
and not in
:
>>> text = "Who are you?"
>>> "r" in text
True
>>> "ou" not in text
False
Immutability
Strings are immutable. Once defined, they can’t be changed:
>>> name = "Jake"
>>> name[2] = "n"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>
We can assign a new object to a variable, but this is not changing the string. We are just defining a new string and assigning it to the same variable:
>>> text = "one" # the string is assigned to text
>>> text = "two" # a new string is assigned to text
>>> text
two'
>>>
We can’t delete a single character either. If we try to do that, using the del statement, we’ll get an error:
>>> name = "Steve"
>>> del name[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion
We can delete the whole string:
>>> del name
>>> name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined
>>>
Slicing
We can slice strings. To do that we specify the startIndex
and pastIndex
in square brackets. The pastIndex
is not included!!!
>>> text = "unbelievable"
>>> text[0:4]
'unbe'
>>> text[4:5]
'l'
If we skip startIndex
, it means: from the beginning (it’s set to 0), so [:6]
is the same as [0:6]
:
>>> text[:8]
'unbeliev'
If we skip pastIndex
, it means: to the end:
>>> text[3:]
'elievable'
We can use negative indices as well:
>>> text[:-5]
'unbelie'
We can copy the whole string slicing the whole of it. We just omit the indices in the square brackets [:]
:
>>> text[:]
'unbelievable'
We can also slice sequences so that only every third or every fifth element is taken. We just need to set the step as the third argument in the square brackets: [startIndex : pastIndex : step]
>>> text[2:10:2]
'blea'
>>> text[::3]
'ueeb'
>>> text[::-1]
'elbaveilebnu'
Concatenation
We concatenate strings using the + sign:
>>> "Hello" + " " + "kids!" # literals
'Hello kids!'
>>> daughter = "Alice" # variables
>>> son = "Josh"
>>> "I have a present for " + daughter + " and " + son + "."
'I have a present for Alice and Josh.'
Repetition
We use the multiplication operator *
with strings to repeat them:
>>> "ho" * 5
'hohohohoho'
Escape Sequences
Escape characters / sequences are characters or sequences used to escape the special meaning of another character.
Examples:
\n | newline |
This sequence is used for a new line:
>>> a = "yes \nor \nno?"
>>> print(a)
yes
or
no?
Escape sequences don’t work if we echo strings:
>>> a
'yes \nor \nno?'
\t | horizontal tab |
This sequence adds tabs:
>>> a = "We need more \t\t\t\t\t\t\t tabs!"
>>> print(a)
We need more tabs!
\\ | backslash |
This sequence should be used if you need a single backslash:
>>> a = "I need a single \\ here."
>>> print(a)
I need a single \ here.
Raw Strings
If we want to print an escape sequence literally, we can use a raw string. To do so, we have to precede the opening quote with a small or capital letter R:
>>> print(r"one \n two") # a raw string
one \n two
Otherwise we would get:
>>> print("one \n two") # not a raw string
one
two
Formatting Strings
There are several ways of formatting strings. The two preferable ones are using the format
method and f-strings.
The format
method takes two kinds of parameters: positional parameters and keyword parameters. Positional parameters are accessed by index, keyword parameters are accessed by keyword. We use placeholders inside the strings.
Let’s start with something simple, a template with just one format field and one positional parameter in the format
method:
>>> text = "I like {} and baseball.".format("soccer")
>>> print(text)
I like soccer and baseball.
Here the format code within the curly braces is empty. We could also have more parameters and format fields:
>>> text = "They bought 5 {}, 3 {} and some {}.".format("apples", "bananas", "oranges")
>>> print(text)
They bought 5 apples, 3 bananas and some oranges.
Alternatively, we could use the indices of the positional parameters in the format fields for clarity. We can use them in any order and as many times as we want:
>>> text = '''
... They bought 5 {1}, 3 {2} and some {0}.
... The next day they bought even more {1},
... but not any {0} or {2}.
... '''.format("apples", "bananas", "oranges")
>>> print(text)
They bought 5 bananas, 3 oranges and some apples.
The next day they bought even more bananas,
but not any apples or oranges.
Now, how do we use keyword parameters? Let’s have a look:
>>> text = "Her name was {name}, she was {age} and was a {job}.".format(age = 45, name = "Lucinda", job = "musician")
>>> print(text)
Her name was Lucinda, she was 45 and was a musician.
We can also mix positional and keyword parameters. Positional parameters must always come first in the method:
>>> text = "He went to {0}, then to {1} and finally to {destination}.".format("Florida", "Georgia", destination = "Ohio")
>>> print(text)
He went to Florida, then to Georgia and finally to Ohio.
And here’s how f-strings work: we have placeholders embedded in the string. Such strings are prefixed with f
:
>>> weight = 24
>>> f"Weight in kilograms: {weight}"
'Weight in kilograms: 24'
>>> f"Weight in grams: {weight * 1000}"
'Weight in grams: 24000'
String Methods
There are lots of string methods we can use. If we want to turn all letters to uppercase, we should use the upper
method:
>>> "hello".upper()
'HELLO'
If we want to turn all letters to lowercase, we should use the lower
method:
>>> "Watch the ball. STOP!".lower()
'watch the ball. stop!'
The len
method returns the length of a string:
>>> len("hello")
5
The method count
counts how many times a substring occurs in a string:
>>> text = "She helped her, but he hesitated."
>>> text.count("he")
5
We use the method find
to find the index at which a substring is in the string:
>>> text = "Find me if you can!"
Where is “me” in the string?
>>> text.find("me")
5
We use the startswith
and endswith
methods to check if a string starts or ends with a substring:
>>> "hello".startswith("hem")
False
>>> "hello".endswith("o")
True
>>> "hello".startswith("l", 2, 4) # check between index 2 and 3
True
The method join
takes the string elements from a sequence and concatenates them using the string as the separator:
>>> separator = " <*> "
>>> sequence = "star"
>>> separator.join(sequence)
's <*> t <*> a <*> r'
The method split
splits a string into a list of substrings using a delimiter character as the position to split. The delimiter is not included in the result. If no delimiter is given, it defaults to whitespace:
>>> text = "This text is so long. Why not have a list of shorter ones?"
If there are no arguments, the whole string is split on the whitespaces:
>>> text.split()
['This', 'text', 'is', 'so', 'long.', 'Why', 'not', 'have', 'a', 'list', 'of', 'shorter', 'ones?']
Now let’s split on the period:
>>> text.split(".")
['This text is so long', ' Why not have a list of shorter ones?']
We can replace substrings with other substrings by using the method replace
:
>>> text = "She is waiting, but she is impatient."
>>> text.replace("is", "was")
'She was waiting, but she was impatient.'
QUIZ
1. Strings are …-based in the forward direction. |
A) 0 |
B) 1 |
C) -1 |
2. Using the del keyword we can delete: |
A) a single character |
B) part of the string |
C) the whole string |
3. To escape characters we use the … character: |
A) / |
B) \ |
C) r or R |
4. The horizontal tab escape character is: |
A) \n |
B) \h |
C) \t |
5. Placeholders are contained in: |
A) parentheses |
B) square brackets |
C) curly braces |
6. The … method returns the length of a string. |
A) count |
B) len |
C) length |
TRUE OR FALSE?
1) We can use triple double quotes or triple single quotes. |
2) Strings are immutable. |
3) We can copy the whole string slicing it with [:] . |
4) We use the multiplication operator * with strings to repeat them. |
5) Escape sequences don’t work if we echo strings. |
6) A raw string is a string with suppressed escape sequences. |
7) Keyword parameters must always come before positional ones in the format method. |
8) The method split splits a string into a list of substrings using a delimiter which is included in the result. |
WHAT’S THE OUTPUT?
1) >>> text = 'I\'d like Jane\'s car.' |
2) >>> text = "They said: \"We won't do it.\"" |
3) >>> name = "Jane" |
4) >>> len('hello') |
5) >>> c = "New York" |
6) >>> x = "hello" |
7) >>> "Good" == "good" |
8) >>> "hey" > "hen" |
9) >>> "p" not in "Paris" |
10) >>> word = "interesting" |
11) >>> word = "nice" |
12) >>> word = "mustard" |
13) >>> word = "believe" |
14) >>> word = "structure" |
15) >>> a = "good" |
16) >>> x = "x" |
17) >>> a = "one two \nthree" |
18) >>> a = "one two \nthree" |
19) >>> a = "one two \tttthree" |
20) >>> print(r"My favorite escape characters are \n, \t, \', \" and \\.") |
21) >>> names = ("Harry", "Joe", "Mike") |
22) >>> text = "We met {0}, then {1} and finally {2} and {2}'s sister {3}.".format("Jack", "Tom", "Anne", "Natalie") |
23) >>> text = "{name}'s {ord}th son lives in {city}.".format(ord = 4, name = "John", city = "Munich") |
24) >>> text = "He likes {0} and {1} but he doesn't like {sport}.".format("soccer", "baseball", sport = "rugby") |
25) >>> x = 28 |
26) >>> a = "come on " |
27) >>> x = 'elle' |
28) >>> x = 'go' |
29) >>> separator = '<>' |
30) >>> a = "seven" |
31) >>> text = "fourth, sixth, seventh, tenth" |
SOLUTION
QUIZ
1. Strings are …-based in the forward direction. |
A) 0 |
B) 1 |
C) -1 |
2. Using the del keyword we can delete: |
A) a single character |
B) part of the string |
C) the whole string |
3. To escape characters we use the … character: |
A) / |
B) \ |
C) r or R |
4. The horizontal tab escape character is: |
A) \n |
B) \h |
C) \t |
5. Placeholders are contained in: |
A) parentheses |
B) square brackets |
C) curly braces |
6. The … method returns the length of a string. |
A) count |
B) len |
C) length |
TRUE OR FALSE?
1) We can use triple double quotes or triple single quotes. True |
2) Strings are immutable. True |
3) We can copy the whole string slicing it with [:] . True |
4) We use the multiplication operator * with strings to repeat them. True |
5) Escape sequences don’t work if we echo strings. True |
6) A raw string is a string with suppressed escape sequences. True |
7) Keyword parameters must always come before positional ones in the format method. False |
8) The method split splits a string into a list of substrings using a delimiter which is included in the result. False |
WHAT’S THE OUTPUT?
1) >>> text = 'I\'d like Jane\'s car.' Output: |
2) >>> text = "They said: \"We won't do it.\"" Output: They said: "We won't do it." |
3) >>> name = "Jane" Output: 'Je' |
4) >>> len('hello') Output: 5 |
5) >>> c = "New York" Output: 8 |
6) >>> x = "hello" Output: 'ee hello' |
7) >>> "Good" == "good" Output: False |
8) >>> "hey" > "hen" Output: True |
9) >>> "p" not in "Paris" Output: True |
10) >>> word = "interesting" Output: 'in rest' |
11) >>> word = "nice" Output: 'ice' |
12) >>> word = "mustard" Output: 'must' |
13) >>> word = "believe" Output: 'believe' |
14) >>> word = "structure" Output: 'eucr' |
15) >>> a = "good" Output: 'oo|||oo|||oo|||' |
16) >>> x = "x" Output: 'xxxx' |
17) >>> a = "one two \nthree" Output: one two |
18) >>> a = "one two \nthree" Output: 'one two \nthree' |
19) >>> a = "one two \tttthree" Output: one two ttthree |
20) >>> print(r"My favorite escape characters are \n, \t, \', \" and \\.") Output: My favorite escape characters are \n, \t, \', \" and \\. |
21) >>> names = ("Harry", "Joe", "Mike") Output: Her sons are Mike, Harry and Joe. |
22) >>> text = "We met {0}, then {1} and finally {2} and {2}'s sister {3}.".format("Jack", "Tom", "Anne", "Natalie") Output: We met Jack, then Tom and finally Anne and Anne's sister Natalie. |
23) >>> text = "{name}'s {ord}th son lives in {city}.".format(ord = 4, name = "John", city = "Munich") Output: John's 4th son lives in Munich. |
24) >>> text = "He likes {0} and {1} but he doesn't like {sport}.".format("soccer", "baseball", sport = "rugby") Output: He likes soccer and baseball but he doesn't like rugby. |
25) >>> x = 28 Output: 'y = 64.0' |
26) >>> a = "come on " Output: 'COME ON come on ' |
27) >>> x = 'elle' Output: True |
28) >>> x = 'go' Output: True |
29) >>> separator = '<>' Output: o<>n<>e |
30) >>> a = "seven" Output: ['The ', 'an and other ', 'ehicles arri', 'ed.'] |
31) >>> text = "fourth, sixth, seventh, tenth" Output: 'four , six , seventh, ten' |
PROJECT
'''
Escape Sequences and Raw Strings - Project
N CHARACTERS PER LINE
__________________________________________________________
Your task is to write a program that will ask the user to enter a string
of any length and the number of characters per line (n). Then it will print
the text on several lines with n characters on each line.
GUIDELINES AND HINTS
- Use escape sequences for newlines where necessary. Don't use print()
to print an empty line. Instead add newline characters to other
strings.
- The text is to be printed on several lines. Use a while loop that will
run as long as the the line number is less than or equal to the number
of characters divided by the number of characters per line.
- Use slicing to slice the text into n-character substrings (n is the number
of characters per line). You can use complex expressions in the square
brackets as start index and past index.
POSSIBLE OUTPUT
Enter your text below:
Congratulations! You did really great.
How many characters per line? 5
Here's your text rewritten with 5 characters per line:
Congr
atula
tions
! You
did
reall
y gre
at.
'''
########## Write your code below. ##########
PROJECT SOLUTION
text = input("Enter your text below: \n")
chars_per_line = int(input("\nHow many characters per line? ")) # \n for empty line
print("\nHere's your text rewritten with " + str(chars_per_line)
+ " characters per line: \n")
line_number = 0 # starting row
while line_number <= (len(text) // chars_per_line):
# code may span multiple lines when enclosed in (), [] or {}
line = text[line_number * chars_per_line :
chars_per_line * (line_number + 1)] # slicing
print(line)
line_number += 1