Python M3
Python M3
Since the string begins with a double quote, Python knows that the single quote is part of the
string and not marking the end of the string.
Escape Characters
If you need to use both single quotes and double quotes in the string, you’ll need to use escape
characters.
An escape character consists of a backslash (\) followed by the character you want to add to the
string.
Python knows that the single quote in Bob\'s has a backslash, it is not a single quote meant to end
the string value. The escape characters \' and \" allows to put single quotes and double quotes
inside your strings, respectively.
Ex:
The different special escape characters can be used in a program as listed below in a table.
Raw Strings
You can place an r before the beginning quotation mark of a string to make it a raw string. A raw
string completely ignores all escape characters and prints any backslash that appears in the string.
Output
The following print() call would print identical text but doesn’t use a multiline string.
Multiline Comments
While the hash character (#) marks the beginning of a comment for the rest of the line.
A multiline string is often used for comments that span multiple lines.
The space and exclamation point are included in the character count, so 'Hello world!' is 12
characters long.
If we specify an index, you’ll get the character at that position in the string.
If we specify a range from one index to another, the starting index is included and the ending index
is not.
The substring we get from spam[0:5] will include everything from spam[0] to spam[4], leaving out
the space at index 5.
Note: slicing a string does not modify the original string.
The in and not in Operators with Strings
The in and not in operators can be used with strings just like with list values.
An expression with two strings joined using in or not in will evaluate to a Boolean True or False.
These expressions test whether the first string (the exact string, case sensitive) can be found within
the second string.
These methods do not change the string itself but return new string values.
If we want to change the original string, we have to call upper() or lower() on the string and then
assign the new string to the variable where the original was stored.
The upper() and lower() methods are helpful if we need to make a case-insensitive comparison.
In the following small program, it does not matter whether the user types Great, GREAT, or
grEAT, because the string is first converted to lowercase.
Program Output
The isupper() and islower() methods will return a Boolean True value if the string has at least one
letter and all the letters are uppercase or lowercase, respectively. Otherwise, the method returns False.
Since the upper() and lower() string methods themselves return strings, you can call string methods
on those returned string values as well. Expressions that do this will look like a chain of method calls.
The isX string methods are helpful when you need to validate user input.
For example, the following program repeatedly asks users for their age and a password until they
provide valid input.
Program output
These methods are useful alternatives to the == equals operator if we need to check only whether
the first or last part of the string, rather than the whole thing, is equal to another string.
string join() calls on is inserted between each string of the list argument.
o Ex: when join(['cats', 'rats', 'bats']) is called on the ', ' string, the returned string is 'cats, rats,
bats'.
o join() is called on a string value and is passed a list value.
Split()
The split() method is called on a string value and returns a list of strings.
We can pass a delimiter string to the split() method to specify a different string to split upon.
A common use of split() is to split a multiline string along the newline characters.
Passing split() the argument '\n' lets us split the multiline string stored in spam along the newlines
and return a list in which each item corresponds to one line of the string.
Justifying Text with rjust(), ljust(), and center()
The rjust() and ljust() string methods return a padded version of the string they are called on, with
spaces inserted to justify the text.
The first argument to both methods is an integer length for the justified string.
'Hello'.rjust(10) says that we want to right-justify 'Hello' in a string of total length 10. 'Hello' is five
characters, so five spaces will be added to its left, giving us a string of 10 characters with 'Hello'
justified right.
An optional second argument to rjust() and ljust() will specify a fill character other than a space
character.
The center() string method works like ljust() and rjust() but centers the text rather than justifying it
to the left or right.
These methods are especially useful when you need to print tabular data that has the correct
spacing.
In the below program, we define a printPicnic() method that will take in a dictionary of information
and use center(), ljust(), and rjust() to display that information in a neatly aligned table-like format.
o The dictionary that we’ll pass to printPicnic() is picnicItems.
o In picnicItems, we have 4 sandwiches, 12 apples, 4 cups, and 8000 cookies. We want to
organize this information into two columns, with the name of the item on the left and the
quantity on the right.
Program output
Optionally, a string argument will specify which characters on the ends should be stripped.
Passing strip() the argument 'ampS' will tell it to strip occurences of a, m, p, and capital S from the
ends of the string stored in spam.
The order of the characters in the string passed to strip() does not matter: strip('ampS') will do the
same thing as strip('mapS') or strip('Spam').
Copying and Pasting Strings with the pyperclip Module
The pyperclip module has copy() and paste() functions that can send text to and receive text from
your computer’s clipboard.
Of course, if something outside of your program changes the clipboard contents, the paste()
function will return it.
This new code looks in the PASSWORDS dictionary for the account name. If the account name is a
key in the dictionary, we get the value corresponding to that key, copy it to the clipboard, and print
a message saying that we copied the value. Otherwise, we print a message saying there’s no account
with that name.
On Windows, you can create a batch file to run this program with the win-R Run window. Type the
following into the file editor and save the file as pw.bat in the C:\Windows folder:
With this batch file created, running the password-safe program on Windows is just a matter of
pressing win-R and typing pw <account name>.
Program output
Step 1: Copy and Paste from the Clipboard
You want the bulletPointAdder.py program to do the following:
1. Paste text from the clipboard
2. Do something to it
3. Copy the new text to the clipboard
Steps 1 and 3 are pretty straightforward and involve the pyperclip.copy() and pyperclip.paste()
functions. saving the following program as bulletPointAdder.py:
We split the text along its newlines to get a list in which each item is one line of the text. For each
line, we add a star and a space to the start of the line. Now each string in lines begins with a star.
Step 3: Join the Modified Lines
The lines list now contains modified lines that start with stars.
pyperclip.copy() is expecting a single string value, not a list of string values. To make this single
string value, pass lines into the join() method to get a single string joined from the list’s strings.
When this program is run, it replaces the text on the clipboard with text that has stars at the start of
each line.