Main Content

Python - some common questions answered in code examples

Archive - Originally posted on "The Horse's Mouth" - 2010-10-10 10:17:14 - Graham Ellis

Some tips and new examples from last week ... Python in Plymouth!

• How do I put comments in a Python regular expression to make it more readable: [source]

• How do I use a python dictionary as a table of counters - in our example, counting the number of people in our team who have each of a whole series of skills: [source]

• How do I replace a string you've matched in a Python regular expression with a literal string, with a string which includes part of the matched text, and with the result of running a piece of code on the matched text: [source]

• How do I convert a python program that reads a whole file in then processes it all into one that processes each line as it has read it (using a generator): [source] and [data]

• How do I run a block of python code every time I leave a try block, even if you are breaking or returning: [source]

• How do lists and strings and tuples differ when I copy them - mutable v immutable: [source]

• How do I manipulate python lists - insert and delete items, add things on to the end, etc: [source]

• How do I write python strings in different ways - raw and cooked, single line and multiline, unicode, etc: [source]

• "Have you an example in Python that shows many / most / all of the OO features of the language in a single practical example". In truth, the answer always has to be "no" as there are quite a lot of features used only rarely, and we really have to contrive an example to show a lot of them. But here are a couple: [source] of an example that uses a static method, comparators, operator overriding, polymorphism and interitance, etc. And [source] a simpler example that loads data into Python objects using a wholesale factory method. The data for that latter is [here].

See [here] for details of our public courses in Python. We also run courses on site (for groups of 4 or more delegates) which can be tailored to meet your needs, and scheduled to suit your requirements too.