Archive for February, 2017


February 9, 2017 Leave a comment

A namedtuple can be used as a simple class where you want to group together some attributes, you want to name them, and you don’t need any methods. As its name suggests, it’s a tuple, but you can assign names to the attribues.


from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])    # name of the "struct" and its attributes
# Point = namedtuple('Point', 'x y')       # it would also work, and it means the same
                                           # the 2nd parameter can be a single space-delimited string

def main():
    p = Point(x=1, y=4)
    print(p)                # Point(x=1, y=4)
    p = Point(1, 4)
    print(p)                # Point(x=1, y=4)
    print(p.x)              # 1
    print(p[0])             # 1
    print(p == (1, 4))      # True
Categories: python Tags: ,

creating a list of strings

February 5, 2017 1 comment

Have you aver written something like this?

>>> li = ["one", "two", "three", "four"]
>>> li
['one', 'two', 'three', 'four']

When I type in all those quotation marks and commas, I always feel sorry for my finger joints. Is there an easier way? Yes, there is:

>>> li = "one two three four".split()
>>> li
['one', 'two', 'three', 'four']
Categories: python Tags: ,

remove punctuations from a text

February 5, 2017 Leave a comment

You have a text and you want to remove punctuations from it. Example:

"Hello! It is time to remove punctuations. It is easy, you will see."

"Hello It is time to remove punctuations It is easy you will see"

Let’s see a Python 3 solution:

>>> import string
>>> tr = str.maketrans("", "", string.punctuation)
>>> s = "Hello! It is time to remove punctuations. It is easy, you will see."
>>> s.translate(tr)
'Hello Its time to remove punctuations Its easy youll see'

Docs: str.maketrans(), str.translate().

Categories: python Tags: , ,