Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

3.1 Strings revisited

Learning objectives

By the end of this section you should be able to

  • Extract a specific character from a string using an index.
  • Use escape sequences to represent special characters.

Indexes

A string is a sequence of zero or more characters. Each character has an index that refers to the character's position. Indexes are numbered from left to right, starting at 0. Indexes are also numbered from right to left, starting at -1.

Unicode

Python uses Unicode, the international standard for representing text on computers. Unicode defines a unique number, called a code point, for each possible character. Ex: "P" has the code point 80, and "!" has the code point 33.

The built-in ord function converts a character to a code point. Ex: ord("P") returns the integer 80. Similarly, the built-in chr function converts a code point to a character. Ex: chr(33) returns the string "!".

Unicode is an extension of ASCII, the American Standard Code for Information Interchange. Originally, ASCII defined only 128 code points, enough to support the English language. Unicode defines over one million code points and supports most of the world's written languages.

Special characters

An escape sequence uses a backslash (\) to represent a special character within a string.

Table 3.2 Common escape sequences.
Escape sequenceMeaningExampleScreen output
\nA newline character that indicates the end of a line of text.print("Escape\nsequence!")Escape
sequence!
\tA tab character; useful for indenting paragraphs or aligning text on multiple lines.print("Escape\tsequence!")Escape    sequence!
\'A single quote; an alternative to enclosing the string in double quotes.print('I\'ll try my best!')I'll try my best
\"A double quote; an alternative to enclosing the string in single quotes.print("I heard you said \"Yes\"")I heard you said "Yes"
\\A backslash character.print("This prints a \\")This prints a \