= 'HELLO WORLD'
message print(message)
HELLO WORLD
The string
datatype represents textual messages, comprised of any number of alphanumeric characters.
There are three ways to construct a string: by using single quotes, double quotes, or a multi-line string.
Single quotes ('
) on the extremities:
Double quotes ("
) on the extremities:
Multiline string, uses triple quotes ("""
) on the extremities:
message = """
This is a menu for our trading platform.
To get started, follow these instructions:
1. __________
2. ____________
3. _____________
"""
print(message)
This is a menu for our trading platform.
To get started, follow these instructions:
1. __________
2. ____________
3. _____________
In practice, for single line strings, we can prefer to default to double quotes, because it allows us to use single quotes for contractions, whereas the reverse would break the quoting level:
In practice, some common operations we perform with strings include concatenation, case manipulation, and substring checking, among others.
As an alternative to concatenation, we can use a format string to dynamically compile a string.
Recall that we are not able to concatenate strings with non-string datatypes such as numbers. To overcome this limitation, we could use string conversion function, or more commonly, a format string.
The format string allows us to inject one or more variables into a string.
To implement a format string, we need the letter f
immediately preceding the string. And we need curly braces ({}
) inside the string. This allows us to inject a variable inside the curly braces:
We can use a formatting directive such as :.2f
to format a number to two decimal places, for example to format a number as US Dollars (USD):
A formatting directive such as :,
to use a thousands separator:
Notice, it is possible to inject multiple variables in the format string, and to mix and match formatting directives:
Converting to all uppercase:
Converting to all lowercase:
Converting to title case, where the first letter of each word is capitalized:
We can use the inclusion operator to perform substring checking:
Note this is case sensitive:
It is possible to replace all instances of a substring within a larger string:
A string is like a list of individual characters.
Like a list, we can use the len
function to count the number of characters in a string:
Similar to list operations, we can use indices to reference a specific character in the string, or a sequence of characters (i.e. string slicing):
The split
method will split a string on a designated delimiter: