X Tutup
Skip to content

Latest commit

 

History

History
100 lines (67 loc) · 2.65 KB

File metadata and controls

100 lines (67 loc) · 2.65 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

String Formatting

% operator

name = 'Pete'
'Hello %s' % name

We can use the %x format specifier to convert an int value to a string:

num = 5
'I have %x apples' % num

Note: For new code, using str.format or f-strings is strongly recommended over the % operator.

str.format

Python 3 introduced a new way to do string formatting that was later back-ported to Python 2.7. This makes the syntax for string formatting more regular.

name = 'John'
age = 20'

"Hello I'm {}, my age is {}".format(name, age)
"Hello I'm {0}, my age is {1}".format(name, age)

The official Python 3.x documentation recommend str.format over the % operator:

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the str.format() interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.

Lazy string formatting

You would only use %s string formatting on functions that can do lazy parameters evaluation, the most common being logging:

Prefer:

name = "alice"
logging.debug("User name: %s", name)

Over:

logging.debug("User name: {}".format(name))

Or:

logging.debug("User name: " + name)

Formatted String Literals or f-strings

Python 3.6+

name = 'Elizabeth'
f'Hello {name}!'

It is even possible to do inline arithmetic with it:

a = 5
b = 10
f'Five plus ten is {a + b} and not {2 * (a + b)}.'

Template Strings

A simpler and less powerful mechanism, but it is recommended when handling format strings generated by users. Due to their reduced complexity template strings are a safer choice.

from string import Template

name = 'Elizabeth'
t = Template('Hey $name!')
t.substitute(name=name)
X Tutup