A string object is a piece of text, or in otherwords, a collection of characters. When defining a string, we must put the characters that compose it inside either single or double quotes. These quotes are what allows Python to distinguish between a string and a command.
my_string = "Hello world!"
print(my_string)
type(my_string)
The print()
function is able to take several strings as arguments.
a = "foo"
b = "bar"
print(a, b)
An escape sequence is a sequence of characters that Python applies special meaning to when it encounters them in a string. Several common escape sequences are listed below.
Escape Character | Result |
---|---|
\' | Prints a single quote. |
\" | Prints a double quote. |
\n | Inserts a new line. |
\t | Inserts a tab. |
quote = "\"Python is awesome\", he said."
print(quote)
tale2cities = "It was the best of times.\nIt was the worst of times."
print(tale2cities)
print("Regular.")
print("\tIndented.")
print("\t\tDouble indented.")
When the + symbol is used between strings, it combines, or concatenates the strings.
a = "star"
b = "wars"
c = a + b
print(c)
d = a + " " + b
print(d)
If we try to combine a string and a number with +, we will get an error.
print("one" + 2)
Note that numbers enclosed with quotes are also considered strings. Python does not recongnize them as numbers.
print("1" + 2)
Although we are not able to "add" strings to numbers, we are able to "multiply" a string by a number.
print("blah " * 5)
Since the product of a string and an integer produces another string, expressions of this type can be concatenated together.
print("la " * 4 + "doo " * 3)
Python does NOT know how to "multiply" two strings.
a = "foo"
b = "bar"
print(a*b)
Python has several built-in functions for working with strings.
The len()
function allows you to determine the length of a string.
x = "There are 39 characters in this string."
print(len(x))
The majority of the functions we will encounter when working with strings are methods. The difference between a method and other types of functions we will encounter is subtle, and is not something we are yet ready to fully dive into. For now, we simply note the following two points regarding methods:
myString = "There's a method in the madness."
print(myString.upper())
print(myString.lower())
print(myString.title())
print( myString.count("m") )
print( myString.count("e") )
a = "a "
b = "no "
print( myString.replace(a, b) )
We will often wish to print statements that involve both strings and numeric variables. To accomplish this, we can convert the numeric objects to strings using the str()
function.
x = 129
x2 = x**2
my_string = "The square of " + x + " is " + x2 + "."
my_string = "The square of " + str(x) + " is " + str(x2) + "."
print(my_string)