Python tips and tricks

Nivedita Datta's photo
Nivedita Datta

Published on Aug 11, 2021

2 min read

Remove all punctuation marks from a string using translate.

>>> import string
>>> translator = str.maketrans('', '', string.punctuation)
>>> s = "Ti's a $tr!ng w!t# l0t$ of 'punctuat!0nS', let's translate!"
>>> print(s.translate(translator))
Tis a trng wt l0t of punctuat0nS lets translate

Remove all punctuation marks using re

>>> import re
>>> import string
>>> s = "Ti's a $tr!ng w!t# l0t$ of 'punctuat!0nS', let's translate!"
>>> re.sub(rf"[{string.punctuation}]", "", s)
'Tis a trng wt l0t of punctuat0nS lets translate'

Calculate length of an iterable without using inbuilt length function.

>>> arr = [3,5,2,8,7,1]
>>> sum(map(lambda x:1,arr))
6
>>> set1 = (3,1,6,5,9,0)
>>> sum(map(lambda x:1, set1))
6

use id to check if two variables point to the same object or not

>>> l1 = [3,5,6]
>>> l2 = l1
>>> id(l1)
1541071874632
>>> id(l2)
1541071874632
>>> l2[2]=999
>>> l1
[3, 5, 999]
>>> l2
[3, 5, 999]
<table>
{% for key, value in result.items %}
   <tr>
        <th> {{ key }} </th>
        <td> {{ value }} </td>
   </tr>
{% endfor %}
</table>

Get key with max value in a python dict

>>> stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}
>>> 
>>> max(stats.keys(), key=(lambda key: stats[key]))
'b'

Pad a number or string with zero

>>> # For string
>>> n = '4'
>>> print(n.zfill(3))
004
>>> # For numbers, python >= 3.6
>>> n = 4
>>> print(f'{n:03}') 
004
 
Share this