Encoding and Decoding Strings (in Python 3.x)

Encoding and Decoding Strings (in Python 3.x)

In our other article, Encoding and Decoding Strings (in Python 2.x), we looked at how Python 2.x works with string encoding. Here we will look at encoding and decoding strings in Python 3.x, and how it is different. Encoding/decoding strings in Python 3.x vs Python 2.x Many things in Python 2.x did not change very drastically when the language branched off into the most current Python 3.x versions. The Python string is not one of those things, and in fact it is probably what changed most drastically. The changes it underwent are most evident in how strings are handled in encoding/decoding in Python 3.x as opposed to Python 2.x. Encoding and decoding strings in Python 2.x was somewhat of a chore, as you might have read in another article. Thankfully, turning 8-bit strings into unicode strings and vice-versa, and all the methods in between the two is forgotten in Python 3.x. Let’s examine what this means by going straight to some examples. We’ll start with an example string containing a non-ASCII character (i.e., “ü” or “umlaut-u”): s = ‘Flügel’ Now if we reference and print the string, it gives us essentially the same result: >>> s ‘Flügel’ >>> print(s) Flügel In contrast to…

Writing Your First Python Django Application

Writing Your First Python Django Application

Create A Django Project The previous article Introduction to Python’s Django presented an overview of the Django Framework. In this article, we are going to write a simple Django application from scratch. The first step is to create a project using one of Django’s built-in commands django-admin.py. In a Virtualenv, type this command: django-admin.py startproject myblog django-admin.py is a convenient shell executable that provides a list of subcommands to manage a Django application. In the previous example, the subcommand startproject creates a Django project directory structure in the current directory: myblog/ manage.py myblog/ __init__.py settings.py urls.py wsgi.py myblog is the parent directory of your Django project myblog. It can be renamed to anything you like since it’s just a container. manage.py is a command-line utility that lets you interact with the Django project myblog in various ways. This utility is very helpful for debugging or exercising the code. myblog/myblog is the directory that contains the actual Python package for your project. Since it’s a normal Python package, you can import any module or package inside it using normal Python syntax. For example, import myblog.settings import the settings module within the package myblog. myblog/myblog/settings.py is the settings or configuration for your Django project. It contains a list of global configurations which are used throughout the whole project.…

How to Use Python’s xrange and range

How to Use Python’s xrange and range

Python has two handy functions for creating lists, or a range of integers that assist in making for loops. These functions are xrange and range. But you probably already guessed that! 🙂 The Difference Between xrange and range in Python Before we get started, let’s talk about what makes xrange and range different. For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and xrange returns an xrange object. What does that mean? Good question! It means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. If you want to read more in depth about generators and the yield keyword, be sure to checkout the article Python generators and the yield keyword. Okay, now what does that mean? Another good question. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use. This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as…

How to Get a Sub-string From a String in Python – Slicing Strings

How to Get a Sub-string From a String in Python – Slicing Strings

So how do you get a sub-string in Python? Well, Python has a handy dandy feature called “slicing” that can be used for getting sub-strings from strings. But first, we have to go over a couple of things to understand how this works. Slicing Python Objects Strings, in Python, are arrays of characters, except they act a little bit different than arrays. However, you can treat them, for the most part, as arrays. Using this information, we can use Python’s array functionality, called “slicing”, on our strings! Slicing is a general piece of functionality that can be applied to any array-type object in Python. Okay, so here’s a concrete example using a simple array to start off. >>> a = [1,2,3,4,5] >>> # This is slicing! >>> a[:3] [1, 2, 3] As you can see, this gives us a subset of the array up to the 3rd element. Slicing takes in two “arguments” that specify the start and end position you would like in your array. Syntax: array[start:end] So in our example above, if we only wanted the elements 2 and 3, we would do the following: >>> a[1:3] [2, 3] Alright, alright. What does this have to do with sub-strings?…

How to Slice ListsArrays and Tuples in Python

How to Slice Lists/Arrays and Tuples in Python

So you’ve got an list, tuple or array and you want to get specific sets of sub-elements from it, without any long, drawn out for loops? Python has an amazing feature just for that called slicing. Slicing can not only be used for lists, tuples or arrays, but custom data structures as well, with the slice object, which will be used later on in this article. Slicing Python Lists/Arrays and Tuples Syntax Let’s start with a normal, everyday list. >>> a = [1, 2, 3, 4, 5, 6, 7, 8] Nothing crazy, just a normal list with the numbers 1 through 8. Now let’s say that we really want the sub-elements 2, 3, and 4 returned in a new list. How do we do that? NOT with a for loop, that’s how. Here’s the Pythonic way of doing things: >>> a[1:4] [2, 3, 4] This returns exactly what we want. What the heck does that syntax mean? Good question. Let me explain it. The 1 means to start at second element in the list (note that the slicing index starts at 0). The 4 means to end at the fifth element in the list, but not include it. The colon in the middle is how Python’s lists recognize that we want to…

Writing Models for Your First Python Django Application

Writing Models for Your First Python Django Application

The previous article Writing Your First Python Django Application is a step-by-step guide on how to write a simple Django application from scratch. In this article, you will learn how to write models for your new Django application. Software Architectural Patterns Before we dive into the code, let’s review two of the most popular server-side software architectural design patterns: Model-View-Controller and Presentation-Abstraction-Control. Model-View-Controller The Model-View-Controller (MVC) design pattern is a software architecture pattern which separates the presentation of data from the logic of handling user interactions. A model specifies what kind of data gets stored. A view requests data from a model and generates outputs from it. A controller provides logic to change the view‘s presentation or update the model‘s data. Python’s Django vs Ruby on Rails Writing Simple Views for Your First Python Django Application Activate Admin Application for Your Python Django Website Presentation-Abstraction-Control Like MVC, Presentation-Abstraction-Control (PAC) is another popular software architectural pattern. PAC separates the system into layers of components. Within each layer, the presentation component generates output from the input data; the abstraction component retrieves and processes data; and the control component is the middleman between presentation and abstraction which manages the flow of information and the communication between these components. Unlike MVC, where a view talks directly to a model, PAC‘s presentation and abstraction never talk directly to each other and the communication between them is mediated by control. Unlike Django which follows the MVC pattern, the popular content management system Drupal follows…

How to Copy a File in Python with shutil

How to Copy a File in Python with shutil

So you want to know how to copy a file in Python? Good! It’s very useful to learn and most complex applications that you may design will need at least some form of copying files. Copying a Single File in Python Alright, let’s get started. This first section will describe how to copy a single file (not a directory) to another location on the hard disk. Python has a special module called shutil for simple, high level file operations that is useful when copying single files. Here’s an example of a function that will copy a single file to a destination file or folder (with error handling/reporting): import shutil def copyFile(src, dest): try: shutil.copy(src, dest) # eg. src and dest are the same file except shutil.Error as e: print(‘Error: %s’ % e) # eg. source or destination doesn’t exist except IOError as e: print(‘Error: %s’ % e.strerror) And that’s it! We just call that method, and the file is copied. If the source or destination file doesn’t exist, we print an error notifying the user that the operation has failed. If the source and destination files are the same, we don’t copy them and notify the user of the failed operation. How…

How to See if a String Contains Another String in Python

How to See if a String Contains Another String in Python

Ever wanted to see if a string contains a string in Python? Thought it was going to be complicated like C? Think again! Python implements this feature in a very easy to read and easy to implement fashion. There are two ways of doing it, and some will like one way better than the other, so I’ll leave it up to you to decide which one you like better. The First Way: Using Python’s in Keyword The first way to check if a string contains another string is to use the in syntax. in takes two “arguments”, one on the left and one on the right, and returns True if the left argument is contained within the right argument. Here’s an example: >>> s = “It’s not safe to go alone. Take this.” >>> ‘safe’ in s True >>> ‘blah’ in s False >>> if ‘safe’ in s: … print(‘The message is safe.’) The message is safe. You get the idea. That’s all there is to it. The keyword in does all that magical work in the background for you, so there’s no worrying about for loops or anything of that nature. Python Programming – Defining A Function How to Use Python to Multiply Strings | Multiply Strings in Python…

How to Slice Custom ObjectsClasses in Python

How to Slice Custom Objects/Classes in Python

For an introduction to slicing, please view the article How to Slice Lists/Arrays and Tuples in Python. Slicing Your Own Python Objects Alright, that’s all cool, now we know how to slice. But how do we slice our own objects? If I implement an object that has a list, or custom data structure, how do I make it sliceable? First, we define our custom data structure class. from collections import Sequence class MyStructure(Sequence): def __init__(self): self.data = [] def __len__(self): return len(self.data) def append(self, item): self.data.append(item) def remove(self, item): self.data.remove(item) def __repr__(self): return str(self.data) def __getitem__(self, sliced): return self.data[sliced] Here, we declare a class with a list as the back-end of our structure. MyStructure doesn’t really do that much, but you can add, remove, and get items from it, so it’s still useful in a sense. The only method we need to pay attention to in particular here is the __getitem__ method. This method is called whenever we try to get an item from our structure. When we call structure[0], this actually calls the __getitem__ method in the background and returns whatever that method returns. It’s very useful when implementing a list style object. Build Games for Python Using Pygame | What is PyGame? | Basic PyGame Program…

Python for Android The Scripting Layer (SL4A)

Python for Android: The Scripting Layer (SL4A)

The Scripting Layer for Android, SL4A, is an open source application that allows programs written in a range of interpreted languages to run on Android. It also provides a high level API that allows these programs to interact with the Android device, making it easy to do stuff like accessing sensor data, sending an SMS, rendering user interfaces and so on. It’s is really easy to install and it works on any stock Android device, so you don’t need to be root or anything like that. Currently, the Scripting Layer supports Python, Perl, Ruby, Lua, BeanShell, JavaScript and Tcl. It also provides access to the Android system shell, which is actually just a minimal Linux shell. You can find out more about the SL4A project from their website. Python for Android: Using Webviews (SL4A) Python for Android: Android’s Native Dialogs (SL4A) Quick Tip: How to Print a File Path of a Module Why Android’s SL4A is Different There are a couple of other options for running Python on Android, and some are very good, but none offer the flexibility and features of the Scripting Layer. The alternatives really focus on enabling you to create and package a native app using some…