TweetFollow Us on Twitter

Mac in the Shell: Learning Python on the Mac-Part 2

Volume Number: 24
Issue Number: 12
Column Tag: Mac in the Shell

Mac in the Shell: Learning Python on the Mac-Part 2

All about strings

by Edward Marczak

Introduction

Last month, we began a journey to learn the Python programming language on the Mac. Although I'm assuming little to no programming experience, it should certainly enable experienced programmers to get up to speed quickly in Python as well. Last month started with the absolute basics: variables, objects, the interactive interpreter and the inevitable "Hello, World!" program. There was also a small homework assignment to keep your brain engaged with Python. Let's pick up where we left off.

Answer Key

Last month, I ended the column asking you to "write a program that creates two integer variables,"start"and "end" and one string, "text". Have the program print a slice of the string using the variables and a print statement that precedes the string with "The slice is: ". Here's a script that will do just that:

#!/usr/bin/env python
start = 8
end = 12
text = "This is some text"
print "The slice is:",text[start:end]

Simple, no? Well, this is certainly one way to handle it. "One way?" you ask. "How many ways can there be to write this basic code?" you may think. Well, that's why this entire column will focus on strings in Python, string manipulation and other string subtleties.

Before we continue, I'd like to make a distinction in my writing of this topic. When I refer to Python as "Python"-Capital "P"-I'm referring to Python in general: conceptually. When I use "python", I'm specifically referring to the Python runtime engine and language specification. If you notice this shift in the case throughout the article, that's the reason behind it.

OK. Onward.

Let Me Count the Ways

Like many other scripting languages, you may find that there are several ways to accomplish the same goal in Python. Sometimes the route you choose is purely stylistic. Sometimes the choice is "Pythonic"-instead of brute forcing a solution, Python may include some elegant, built-in way of dealing with your issue. Finally, there are just times where certain styles lend themselves to a particular situation better than other styles, so, you'll find yourself switching styles as needed.

Understanding strings in Python is important, as they are part of the collections class, and therefore respond to anything that a collection class will, as we saw with slices.

Strings in Python do take a little getting used to if you've used other scripting languages in the past. Let's get the basics out of the way.

Strings are formed using single, double or triple quotes. Single quotes and double quotes behave the same:

'This is a string'

and

"This is a string"

are treated the same. Both single and double quotes require escape sequences to represent special characters. Like any regular expression, Perl or PHP, special characters that you want represented literally, require a backslash escape. Examples include a quote within the outer quotes:

'Bill, it\'s time to go!'

and general special characters, such as newline:

print "Don't follow me too closely\n\n\n"
print "Is that far enough?"

Triple quotes-either ''' or """-have some special properties. Firstly, they can be multiline. Secondly, quotes are passed literally, but special characters are still recognized. The following will illustrate these points:

print """What on Earth is going on?
How am I spanning multiple lines? You think
this is funny?\n\nIt's "everyone's" opinion that
it isn't.
"""

This outputs:

What on Earth is going on?
How am I spanning multiple lines? You think
this is funny?
It's "everyone's" opinion that
it isn't.

Notice that the newline characters were honored, but there was no need to escape the inner quotes.

Now, triple quotes are useful, but more often than not, you're going to need to intersperse the contents of variables or manipulate strings for output. There are a few ways to handle these scenarios. Let's start with the most simple: automatic string concatenation. To illustrate, we need to look at the print function. The Python print function automatically outputs a newline after printing its entire string of data. The commands:

print "Don't follow me too closely."
print "Is that far enough?"

will display:

Don't follow me too closely.
Is that far enough?

No explicit newline character needed. That's pretty straightforward. One way to get rid of the newline character is to use Python's automatic string concatenation feature. Python doesn't require any specific character to concatenate adjacent strings:

print "String 1" "String 2"

prints "String 1String 2". Easy enough, right? Using parentheses, you can extend this to work with multi-line code:

print ("Don't follow me too closely."
       "Is that far enough?")

A comma, which also concatenates strings, will suppress a newline character. It's also a way to add in variables. You may have noticed the homework assignment string used a comma:

print "The slice is:",text[start:end]

What you may not have noticed is that the comma also inserts a space. (There will be a space between the colon and the text in this example). Another way to concatenate strings is the addition symbol, which is overridden to work with text. This method does not insert a space:

print "The slice is: " + text[start:end]

Notice that we added a space ourselves before the final quote mark.

More useful in many ways is the format string. C programmers will recognize this immediately: Python uses the same string formatters as the printf functions in C. The easy introduction is this: Python's print function will substitute the contents of a variable into a string where it finds the string format specifier %s. Time for an example:

username = "bill"
print "Hello, %s" % username

This trivial example will print, "Hello, bill". In a larger program, we'd likely be fetching the username from some other location, such as a database. This style keeps code much more readable, especially when more variables are substituted in a single string. For example:

print "%s, you have %s credit remaining, " \
      "out of %s total." % (user['first'],
      user['credit'],
      user['total'])

There are a few techniques pointed out here. First, you can use the backslash character to continue long lines. Use it where it makes your code more readable. The parentheses form a tuple-something we'll cover in detail next month. The values in the tuple are substituted into the string in order.

For the sake of completeness, there's one last form that is very useful, but won't make sense until we cover dictionaries. A dictionary is a Python data structure that offers a mapping of keys to values. Keys in a dictionary are unique. Due to this, a print format string will also accept a dictionary to map to:

print "%(first)s, you have %(credit)s credit remaining, " \
      "out of %(total)s total." % user

In this example, user is the dictionary-as in the previous example-and each format specifier contains the key in that dictionary to substitute the value of. This will be covered in future columns.

In order to bring this full circle, this shows another way we could have written the print statement in the homework assigment:

print "The slice is: %s" % text[start:end]

One thing I've glossed over a bit here: we're coercing all values into strings. To illustrate, look at this example:

foo=52
print "The value is %s." % foo

Here, foo is an integer value, but we're placing it into a string. The Python interpreter will happily do the right thing here. But there are situations where you'll need to be a little more precise. In fact, the right way to handle this is to specify that the variable being substituted is an integer. Instead of playing fast and loose and treating all values as a string, "%s", you can specify integers with "%d":

print "The value is %d." % foo

Why does this eally matter, you may ask? Last month, we covered Python's various data types. String, Unicode, integer and float are all used for different purposes. When substituting a float value, you may want to specify the number of decimal places. Try this example:

myfloat = 5.9872345234
print "The number is %s." % myfloat
print "Reduced to 2 decimal places,",\
      "and rounded, it\'s %0.2f" % myfloat

The Python documentation contains a full list of format specifiers. Find it at: http://www.python.org/doc/current/lib/

If you install the documentation as instructed in the next section, this can be found locally at file:///Library/ Frameworks/Python.framework/Versions/2.5/Resources/English.lproj/Documentation/lib/typesseq-strings.html.

All You Need to do is Ask

One thing that I feel is important to teach is showing ways in which you can help yourself. Python was designed with this in mind, and supplies a built-in help system. In the interactive python shell, just type help(), or, look for help on a particular word:

>>> help('print')
Sorry, topic and keyword documentation is not available 
because the Python HTML documentation files could not be found.
If you have installed them, please set the environment
variable PYTHONDOCS to indicate their location.

Ah, yes...you'll run into this under OS X. The documentation is, for some reason, not installed with the out-of-the-box Leopard installation. This is easily remedied, however. Download the PythonMac 2.5 distribution (http://pythonmac.org/packages/py25-fat/dmg/python-2.5-macosx.dmg) and mount the image, but do not run the installer. The installer on the image is a metapackage. Control-click on the included mpkg installer, and choose "Show Package Contents" from the resulting Finder menu. Navigate to Contents/Packages and double-click on PythonDocumentation-2.5.pkg to install the documentation. The docs are dropped onto the boot volume, but buried at /Library/Frameworks/Python.framework/Versions/2.5/Resources/English.lproj/Documentation. Even though they're present on disk, python will still not know where to locate them. Let's fix that. Of course, there needs to be a slight explanation first.

Python uses an environment variable named PYTHONDOCS to locate its documentation. As you may expect, PYTHONDOCS specifies a path in the same format as the shell PATH variable: an absolute path on the filesystem. To enable python to locate the documentation, we can create the PYTHONDOCS variable and add the OS X-specific location. In your shell, type and enter:

export PYTHONDOCS=/Library/Frameworks/Python.framework/Versions/2.5/Resources/English.lproj/Documentation

You need to export the variable so the subshell running the python interpreter inherits the value. Ideally, you should add this to a startup file so it's available each time you start a shell. Dropping it in your ~/.bash_profile file is recommended. There are also two very OS X-ish ways of dealing with this for those of you in a GUI environment. One is to simply open the GUI application from the shell that has the exported variable:

open /Users/Shared/Applications/TextWrangler.app

Just supply open with the full path to the application in question. This will allow the application access to any exported environment variables in that shell session. Since I'm in a shell pretty much full-time, this is my preferred method. Create an alias for the command you use if you do this often.

The second way is to add the environment variable to the user-global environment.plist, or, directly to a particular application's plist. Apple has excellent documentation available on just this topic, so there's no need for me to repeat it. The environment variable developer docs can be found at http://developer.apple.com/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html,. (If Apple ever moves this doc, hit up Google for "User Session Environment Variables").

If you're using TextMate, you can define shell variables in Preferences > Advanced > Shell Variables. Just add a variable named "PYTHONDOCS" with the path listed above, and you can avoid the entire edit-the-plist dance.

Once your environment variable is set, enter python again and ask for help:

>>> help()
Welcome to Python 2.5!  This is the online help utility.
(...output shortened for space considerations...)

Once in the help system, the python prompt will change to help>. You can look for general help on modules, topics or keywords just by typing "modules", "topics" or "keywords" (clever, eh?):

help> modules
Please wait a moment while I gather a list of all available modules...

If you know the module name or keyword, you can just bring up the information directly:

help> print
  ------------
  
  6.6 The print statement
...

Finally, there's no need to enter the help system at all. You can call help with your query as an argument. For example:

>>> help('print')

To exit the help system, press ctrl-d, just like you're leaving the interactive python shell.

For pedantic among you, there's a small distinction to make here. The python interpreter initializes its own environment from the PYTHONDOCS environment variable. Once python is running, changing this variable will have no effect. Conversely, you can look up the current PYTHONDOCS path. From the interactive shell, type the following:

>>> import pydoc
>>> pydoc.help.docdir

python should spit back to you the current path inherited from PYTHONDOCS.

Conclusion

Between last month and this month, you now know everything practical about strings in Python. While there's a good road left to travel in Python itself, the good news is that so much of the work you'll typically do involves strings and collections that this is a great topic to understand. In next column, we'll tackle more. For now, practice with what you have learned so far.

Media of the month: Neuromancer by William Gibson. Every techie needs some William Gibson in their library. If you've already read Neuromancer, but haven't explored more, use this as an opportunity to pick up something more recent (Count Zero and Pattern Recognition come to mind).

Next month is Macworld. Please stop by the MacTech booth and say hello! Until then, keep scripting!


Ed Marczak knew even from the punch card and TTY days that technology was in his future. He finds all technology interesting, but chooses OS X when possible. When not computing, he spends time with his wife and two daughters.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »

Price Scanner via MacPrices.net

Verizon has Apple AirPods on sale this weeken...
Verizon has Apple AirPods on sale for up to 31% off MSRP on their online store this weekend. Their prices are the lowest price available for AirPods from any Apple retailer. Verizon service is not... Read more
Apple has 15-inch M2 MacBook Airs available s...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
May 2024 Apple Education discounts on MacBook...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $300 off the purchase of a new MacBook... Read more
Clearance 16-inch M2 Pro MacBook Pros in stoc...
Apple has clearance 16″ M2 Pro MacBook Pros available in their Certified Refurbished store starting at $2049 and ranging up to $450 off original MSRP. Each model features a new outer case, shipping... Read more
Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more

Jobs Board

Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.