Skip to content

Latest commit

 

History

History
334 lines (238 loc) · 5.22 KB

File metadata and controls

334 lines (238 loc) · 5.22 KB

Python Cheat Sheet

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.

Read It

Manipulating Strings

Escape Characters

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?

Raw Strings

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)

Multiline Strings with Triple Quotes

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.

Indexing and Slicing Strings

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

The in and not in Operators with Strings

'Hello' in 'Hello World'
'Hello' in 'Hello'
'HELLO' in 'Hello World'
'' in 'spam'
'cats' not in 'cats and dogs'

The in and not in Operators with list

a = [1, 2, 3, 4]
5 in a
2 in a

The upper, lower, isupper, and islower String Methods

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()

The isX String Methods

  • isalpha() returns True if the string consists only of letters and is not blank.
  • isalnum() returns True if the string consists only of lettersand numbers and is not blank.
  • isdecimal() returns True if the string consists only ofnumeric characters and is not blank.
  • isspace() returns True if the string consists only of spaces,tabs, and new-lines and is not blank.
  • istitle() returns True if the string consists only of wordsthat begin with an uppercase letter followed by onlylowercase letters.

The startswith and endswith String Methods

'Hello world!'.startswith('Hello')
'Hello world!'.endswith('world!')
'abc123'.startswith('abcdef')
'abc123'.endswith('12')
'Hello world!'.startswith('Hello world!')
'Hello world!'.endswith('Hello world!')

The join and split String Methods

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')

Justifying Text with rjust, ljust, and center

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, '=')

Removing Whitespace with strip, rstrip, and lstrip

spam = '    Hello World     '
spam.strip()
spam.lstrip()
spam.rstrip()
spam = 'SpamSpamBaconSpamEggsSpamSpam'
spam.strip('ampS')

Copying and Pasting Strings with the pyperclip Module

First, install pypeerclip with pip:

pip install pyperclip
import pyperclip

pyperclip.copy('Hello world!')
pyperclip.paste()