Python String Cheat Sheet



  1. Python String Methods Cheat Sheet
  2. Python String Manipulation Cheat Sheet
  3. Python F String Cheat Sheet
  4. Python Quick Reference Guide
  • Welcome to Python Cheatsheet! ☕️ Anyone can forget how to make character classes for a regex, slice a list or do a for loop. This cheat sheet tries to provide a basic reference for beginner and advanced developers, lower the entry barrier for newcomers and help veterans refresh the old tricks.
  • The Ultimate Python Cheat Sheet Keywords Keyword Description Code Examples False, True Boolean data type False (1 2) True (2 1) and, or, not Logical operators → Both are true → Either is true → Flips Boolean True and True # True True or False # True not False # True break Ends loop prematurely while True: break # finite loop.

Python allows the values in a dictionary to be any type – string, integer, a list, another dictionary, boolean, etc. However, keys must always be an immutable data type, such as strings, numbers, or tuples. In the example code block, you can see that the keys are strings or numbers (int or float). The values, on the other hand, are many varied data types. Title: Python Strings Cheat Sheet by NouhaThabet - Cheatography.com Created Date: 3103Z.

Python String Methods Cheat Sheet

Field Width and Alignment

'hey {:10}'.format('hello')

'{:010}'.format(2)

Output: 0000000002

'{:*^30}'.format('text')

Output: *************text*************

Python String Cheat Sheet

Member and Element Access

Python String Manipulation Cheat Sheet

'{0}, {1}, {2}'.format(1, 2, 3)

Output: 1, 2, 3

'{}, {}, {}'.format(1, 2, 3)

Implicit positional arguments (2.7 and above only)

'{value1}, {value2}, {value2}'.format(value1=1, value2=2, value3=3)

Access keyword arguments by name

'{[1]}'.format(['first', 'second', 'third'])

Access element by index

'{.name}'.format(sys.stdin)

Access element attribute

'{[name]}'.format({'name': 'something'})

Access element by key

Numerical Representation

Sheet

'{:x}'.format(100)

Output: 64

'{:X}'.format(3487)

Output: D9F

'{:#x}'.format(100)

Output: 0x64

'{:b}'.format(100)

Output: 1100100

'{:c}'.format(100)

Output: d

'{:d}'.format(100)

Output: 100

'{:,}'.format(1000000)

Output: 1,000,000

'{:o}'.format(100)

Output: 144

'{:n}'.format(100)

Like d, but uses locale information for separators

'{:e}'.format(0.0000000001)

Exponent notation

'{:E}'.format(0.0000000001)

Exponent notation (capital 'E')

'{:f}'.format(3/14.0)

Fixed point

'{:g}'.format(3/14.0)

General format

'{:%}'.format(0.66)

Percentage

'{:.3}'.format(0.214286)

Precision

Python F String Cheat Sheet

Conversions

Python Quick Reference Guide

'{!r}'.format('string')

Output: 'string'

'{!s}'.format(1.53438987)

Output: 1.53438987