What is Python hiding from us? In this article, you will probably find some atypical niceties for yourself that can be used in Python.
1. Chaining comparison operators:
>>> 1 < 5 < 10 True >>> 1 < 11 < 10 False >>> 1 < 11 > 10 True
Of course, all the magic disappears if you add parentheses:
>>> (1 < 11) > 10 False
2.iter and two parameters
The built-in iter function returns an iterator for the passed sequence. But if you pass two parameters, then the first should be a callable object, and the second – the result of calling the first object, at which you need to stop iterating. For example, we read from a file up to the first empty line:
with open('mydata.txt') as fp: for line in iter(fp.readline, ''): process_line(line)
If you enumerate on an enumerated type, you also get indexes in the output:
'a', 'b', 'c', 'd', 'e'] > for index, item in enumerate(a): print index, item ... 0 a 1 b 2 c 3 d 4 e >> a = [
Allows you to easily and beautifully use the syntax with EXPR as VAR for your own objects, functions, etc. Example from the documentation:
from contextlib import contextmanager def tag(name): print "[%s]" % name yield print "[/%s]" % name with tag("h1"): print "foo" ... [h1] foo [/h1]
5. Debug scripts in Python
You can set breakpoints using the module
import pdb pdb.set_trace()
To set a breakpoint anywhere in the script, write a command there
pdbare a few more interesting things described in the documentation .
6. Exchange of variable values
In the 10th grade, in a computer science lesson, we were offered a problem – to swap the values of two variables without using the third. In Python, this is not even a question:
10 > b = 5 > a, b (10, 5) > a, b = b, a > a, b (5, 10)> a =
7. Expanding the list / line
You can quickly expand the list as follows:
>>> a = [1,2,3,4] >>> a[::-1] [4, 3, 2, 1] # Это создаёт новый развёрнутый список. # Развернуть имеющий список: a.reverse()
The same can be done with the line:
"yasoob" > foo[::-1] 'boosay'> foo =
8. Nested list comprehensions
The list comprehensions can use several for :
>>> l = [[1,2,3], [4,5,6]] >>> [lll * 2 for ll in l for lll in ll] [2, 4, 6, 8, 10, 12]
9.rot13, string_escape, unicode_escape encodings
Super secret encryption method Rot13 :
'Hello world!'.encode('rot13') 'Uryyb jbeyq!' 'Uryyb jbeyq!'.decode('rot13') u'Hello world!'
Further. For example, there is a string from an external source, while the string contains literals \ n, \ t, \ r , etc. How do I get a formatted string (essentially do a secure eval )?
'Hello\\n\\rworld!' > s 'Hello\\n\\rworld!' > repr(s) "'Hello\\\\n\\\\rworld!'" > print s.decode('string_escape') Hello world!> s =
unicode_escape works the same way, only with unicode, not strings.
10. Ternary operator in Python
The ternary operator is an abbreviated form of the if-else conditional expression. Here’s a usage example:
is_fat = True state = "fat" if is_fat else "not fat"
This approach allows you to quickly check the condition, and not write several lines of the statement
if. This is often very convenient because it allows you to write more compact code while keeping it readable.