On Github gotgenes / python_fundamentals
Created by Chris Lasher of 5AM Solutions, Inc.
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2011-2013 Christopher D. Lasher # # This software is released under the MIT License. Please see # LICENSE.txt for details. """A collection of common utilities and convenient functions.""" import csv import os.path class SimpleTsvDialect(csv.excel_tab): """A simple tab-separated values dialect. This Dialect is similar to :class:`csv.excel_tab`, but uses ``'\\n'`` as the line terminator and does no special quoting. """ lineterminator = '\n' quoting = csv.QUOTE_NONE csv.register_dialect('simple_tsv', SimpleTsvDialect) def make_csv_reader(csvfile, header=True, dialect=None, *args, **kwargs): """Creates a CSV reader given a CSV file. :param csvfile: a file handle to a CSV file :param header: whether or not the file has header :param dialect: a :class:`csv.Dialect` instance :param *args: passed on to the reader :param **kwargs: passed on to the reader """ if dialect is None: try: dialect = csv.Sniffer().sniff(csvfile.read(1024)) except csv.Error: dialect = csv.excel csvfile.seek(0) if header: csv_reader = csv.DictReader(csvfile, dialect=dialect, *args, **kwargs) else: csv_reader = csv.reader(csvfile, dialect=dialect, *args, **kwargs) return csv_reader
#!/usr/bin/env python # -*- coding: UTF-8 -*- a = 1 b = 2 c = a + b print(c)
>>> a = 1 >>> b = 2 >>> a + b 3
Brought to you by Online Python Tutor
>>> "The value is " + 2 # gives "The value is 2" ???
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't convert 'int' object to str implicitly </module></stdin>
>>> "The value is " + str(2) 'The value is 2' >>> "The value is {}".format(2) # The "Pythonic" way 'The value is 2'
msg = 'Wi nøt trei a høliday in Sweden this yër?'
msg = u"See the løveli lakes"
msg = b'See the l\xc3\xb8veli lakes'
>>> s = '''A triple-quoted ... string can ... preserve ... whitespace ... ''' >>> s 'A triple-quoted\nstring can\n preserve\n whitespace\n'
('a', 'b', 42)
((1, 2),) # single-element tuple containing another
>>> a = (1, 2, (3, 4)) >>> a[0] # access the first element 1 >>> a[-1] # access the last element (3, 4) >>> a[-1][0] # access the first element of the last element 3
>>> a = (1, 2, 3) >>> a[1:3] (2, 3) >>> a[1:] (2, 3) >>> a[:2] (1, 2) >>> a[::2] (1, 3)
>>> a = [81, 82, 83] >>> a[0] 81 >>> a[1] 82 >>> a[:2] [81, 82]Can reassign to lists
>>> a [81, 82, 83] >>> a[0] = 'spam' >>> a ['spam', 82, 83]
>>> a ['spam', 82, 83] >>> a.index('spam') 0 >>> del a[0] >>> a [82, 83] >>> a.remove(83) >>> a [82] >>> elem = a.pop() >>> elem 82 >>> a [] >>> a.append(elem) >>> a [82] >>> a.insert(0, 81) >>> a [81, 82] >>> a.extend([83, 84, 85]) >>> a [81, 82, 83, 84, 85] >>> a[1:1] = ['happy', 'joy'] >>> a [81, 'happy', 'joy', 82, 83, 84, 85]