Strings
In Python, strings represent text objects. Python uses single and double quotes,
'...'
or "..."
, to define a string. We have already used strings when
printing greeting text in the introduction page.
"..."
or'...'
: a string object (text)
Strings can contain quotes and other special characters.
For example, use \n
to include the new line character. As its name suggests,
\n
creates new lines in text files and in the printed output. These types of
characters that start with the backwards slash \
are called escape sequences.
Learn more about special characters and escape sequences such as
\n
(new line) from the official documention.
Multiline Strings
You can define multi-line strings with '''...'''
or """..."""
.
Multi-line strings defined in this way will retain their indentations and lines.
Raw Strings
Sometimes you want Python to not interpret an escape sequence. E.g., you
may want to keep \n
as regular characters \
and n
. For this, create
a raw string by prefixing r
to the string.
- Raw strings produce regular strings but without a need to use the backwards slash
\
(escape) when defining a string - Run the print commands with and without
r
prefix to see the differences between raw and regular Python strings.
String Concatenation and Length
You can concatenate (join) multiple strings together using +
.
string1 + string2 + ...
: produces a new string that is composed of the strings,string1
,string2
, etc. joined together
Use len
function to get a string length, the number of characters in a string.
len(string)
: returns the length of the input string
F-Strings
Formatted strings, f-strings for short, allow you to include and format the value
of Python expression into strings. To define f-string, use f
or F
prefix and
insert Python expressions as placeholders in curly braces {expression}
.
f'... {expression}'
: f-string evaluates the expression inside{...}
first. Then, the result is converted to its string representation.
For instance, the following evaluates an addition, formats, and prints the result as a string.
You are not limited to simple expressions like above, and you can use any valid
Python expression inside the placeholders. E.g., in the code below, we call len
function.
Exercises
E1: Debug a Syntax Error
- Oh no! I broke Python. Fix the following code so that it prints two lines.
E2: Inspect a String Object’s Representation
- Run the following multiline string in the Python shell.
- How does the representation of this string differ from what you’ve entered?
"""Priority One
Insure the return of organism
for analysis."""
You can also use built-in
repr
command withprint(repr(...))
.