Basic cheatsheet for Python mostly based on the book written by Al Sweigart, Automate the Boring Stuff with Python under the Creative Commons license and many other sources.
Escape character | Prints as |
---|---|
\' |
Single quote |
\" |
Double quote |
\t |
Tab |
\n |
Newline (line break) |
\\ |
Backslash |
Example:
print("Hello there!\nHow are you?\nI\'m doing fine.")
Hello there!
How are you?
A raw string completely ignores all escape characters and prints any backslash that appears in the string.
print(r'That is Carol\'s cat.')
Note: mostly used for regular expression definition (see re
package)
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')
To keep a nicer flow in your code, you can use the dedent
function from the textwrap
standard package.
from textwrap import dedent
def my_function():
print('''
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob
''').strip()
This generates the same string than before.
H e l l o w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11
spam = 'Hello world!'
spam[0]
spam[4]
spam[-1]
Slicing:
spam[0:5]
spam[:5]
spam[6:]
spam[6:-1]
spam[:-1]
spam[::-1]
spam = 'Hello world!'
fizz = spam[0:5]
fizz
'Hello' in 'Hello World'
'Hello' in 'Hello'
'HELLO' in 'Hello World'
'' in 'spam'
'cats' not in 'cats and dogs'
a = [1, 2, 3, 4]
5 in a
2 in a
upper()
and lower()
:
spam = 'Hello world!'
spam = spam.upper()
spam
spam = spam.lower()
spam
isupper() and islower():
spam = 'Hello world!'
spam.islower()
spam.isupper()
'HELLO'.isupper()
'abc12345'.islower()
'12345'.islower()
'12345'.isupper()
'Hello world!'.startswith('Hello')
'Hello world!'.endswith('world!')
'abc123'.startswith('abcdef')
'abc123'.endswith('12')
'Hello world!'.startswith('Hello world!')
'Hello world!'.endswith('Hello world!')
join():
', '.join(['cats', 'rats', 'bats'])
' '.join(['My', 'name', 'is', 'Simon'])
'ABC'.join(['My', 'name', 'is', 'Simon'])
split():
'My name is Simon'.split()
'MyABCnameABCisABCSimon'.split('ABC')
'My name is Simon'.split('m')
rjust() and ljust():
'Hello'.rjust(10)
'Hello'.rjust(20)
'Hello World'.rjust(20)
'Hello'.ljust(10)
An optional second argument to rjust() and ljust() will specify a fill character other than a space character. Enter the following into the interactive shell:
'Hello'.rjust(20, '*')
'Hello'.ljust(20, '-')
center():
'Hello'.center(20)
'Hello'.center(20, '=')
spam = ' Hello World '
spam.strip()
spam.lstrip()
spam.rstrip()
spam = 'SpamSpamBaconSpamEggsSpamSpam'
spam.strip('ampS')
First, install pypeerclip
with pip:
pip install pyperclip
import pyperclip
pyperclip.copy('Hello world!')
pyperclip.paste()