Strings
In previous section we declared a string variable message
and printed it to the screen.
message = "Hello, World!"
What exactly is a string? A string is a sequence of characters. In the example above, the string "Hello, World!"
consists of 13 characters: H
, e
, l
, l
, o
, ,
,
, W
, o
, r
, l
, d
, !
.
Strings are one of the most common data types that you'll encounter in Python programs. You can use them to represent names, addresses, messages, and many other kinds of information.
Strings are easy to recognize in Python programs. They are enclosed in single or double quotes. In previous example we used double quotes, but single quotes are also valid:
message1 = "Hello, World!"
message2 = 'Hello, World!'
assert message1 == message2 # make sure they are equal
Both declarations are equivalent.
You can use either single or double quotes, but you should be consistent. If you start a string with a single quote, you should end it with a single quote. If you start it with a double quote, you should end it with a double quote.
It's possible to use single quotes inside a string that is enclosed in double quotes, and vice versa. For instance this program
print('I said, "Hello, World!"')
print("He said, 'Hello, Sarah!'")
produces the following output:
I said, "Hello, World!"
He said, 'Hello, Sarah!'
It's also possible to use the same type of quotes inside a string, but you have to escape them with a backslash \
, for instance:
"I said, \"Hello, World!\""
To include a backslash in a string, you have to escape it with another backslash:
>>> print("C:\\Users\\John")
C:\Users\John
Some Useful String Methods
Python provides a number of useful methods for working with strings. A method is an action that Python can perform on a piece of data. The dot .
after the name of the variable name
in the following example tells Python to make the upper()
method act on the variable.
name = "Linus Torvalds"
print(name.upper())
This program produces the following output:
LINUS TORVALDS
Similarly, the lower()
method changes a string to all lowercase:
name = "Linus Torvalds"
print(name.lower())
with output
linus torvalds
One more method, which we'll use a lot in this book, is title()
.
It changes each word to title case, where each word begins with a capital letter:
name = "linus torvalds"
print(name.title())
which produces the following output:
Linus Torvalds
String Formatting
Very often you'll want to combine several strings, for example if you have first_name
and last_name
variables, you might want to combine them into a single string full_name
. Python provides several ways to do this. In this section we'll look at the f-string
method.
Look at the following example:
first_name = "linus"
last_name = "torvalds"
full_name = f"{first_name} {last_name}"
print(full_name)
and its output:
linus torvalds
First two lines should be familiar to you, we declare two string variables for first and last names. The third line is more interesting
full_name = f"{first_name} {last_name}"
Here, we initialize variable with an f-string. The f stands for format.
An f-string is a string that has an f
at the beginning and curly braces {}
containing expressions that will be replaced with their values.
We can place any valid Python expression inside the curly braces. For example, we can use the title()
method to titleize a string:
first_name: str = "linus"
last_name: str = "torvalds"
full_name: str = f"{first_name} {last_name}"
print(f"Hello, {full_name.title()}!")
which outputs a nicely formatted greeting:
Hello, Linus Torvalds!
Dealing with Whitespaces
Whitespace refers to any nonprinting character, such as spaces, tabs, and end-of-line symbols. You can use whitespace to organize your output so it's easier for users to read.
A table below lists some of the whitespace characters:
Name | Character |
---|---|
Space | ' ' |
Tab | '\t' |
Newline | '\n' |
And here's an example of using tabs and newlines:
print("Languages:\n\tPython\n\tC\n\tJavaScript")
and its output:
Languages:
Python
C
JavaScript
Quite often you'll want to strip whitespace from strings. For example, you might want to remove extra whitespace from the right side of a name before storing it. Python provides a number of methods for stripping whitespace from strings.
The basic methods for removing excess whitespace are rstrip()
, lstrip()
, and strip()
. The lstrip()
method removes whitespace from the left side of a string, rstrip()
removes whitespace from the right side, and strip()
removes whitespace from both sides.
Try to run the following program:
favorite_language = ' python '
print(f"'{favorite_language}'") # original string
print(f"'{favorite_language.rstrip()}'") # right strip
print(f"'{favorite_language.lstrip()}'") # left strip
print(f"'{favorite_language.strip()}'") # strip both sides
and compare the output:
' python '
' python'
'python '
'python'
Removing Prefixes
Another useful method is removeprefix()
. It removes a prefix from a string. For example, if you have an url, you can remove ``
url = 'https://dimakura.github.io'
print(url.removeprefix('https://'))
which produces the following output:
dimakura.github.io
You can also use removesuffix()
to remove a suffix from a string:
print(url.removesuffix('.github.io'))
with output:
https://dimakura
Or you can use both methods simultaneously:
print(url.removeprefix('https://').removesuffix('.github.io'))
which gives
dimakura