GIDNetwork > Beginning Python Tutorial (Part 3)
Register
« Programming Techniques Colonial Marines RPG has moved! »

Beginning Python Tutorial (Part 3)

by: crystalattice - Aug 16, 2005

Sorry it's been so long since the last Python installment. The Navy has me signed up for a leadership course and I had to knock out 8 lessons prior to actually taking the class. I've also been making some changes to the game site that I hope to have complete within the next few weeks. But, onto the lesson...

Strings in Python

Strings in Python are different than most other languages. First off, there are no char types, only single character strings. Strings also can't be changed in-place; a new string object is created whenever you want to make changes to it, such as concatenation.

Here's a list of common string operations:

  • s1 = ' ' : empty string

  • s2 = "knight's" : double quotes

  • block = """ - """ : triple-quoted block

  • s1 + s2 : concatenate

  • s2 * 3 : repeat

  • s2[n] : index

  • len(s2) : length

  • "a %s parrot" %'dead' : string formatting

  • for x in s2 : iteration

  • 'm' in s2 : membership

Empty strings are written as two quotes with nothing in between. The quotes used can be either single or double; my preference is to use double quotes since you don't have to escape the single quote to use it in a string. Triple quoted blocks are for strings that span multiple lines. Python collects the entire text block into a single string with embedded newline characters.

Basic string operations

The "+" and "*" operators are overloaded in Python, letting you concatenate and repeat string objects, respectively. Concatenation combines two (or more) strings into a new string object whereas repeat simply repeats a given string a given number of times. Here are some examples:

Generic Code Example:

>>> len('abc')         # length: number items 
3 
>>> 'abc' + 'def'       # concatenation: a new string 
'abcdef' 
>>> 'Ni!' * 4           # like "Ni!" + "Ni!" + ... 
'Ni!Ni!Ni!Ni!'

You need to be aware that Python doesn't automatically change a number to a string, so writing 'spam' + 3 will give you an error.

Iteration in strings is a little different than I'm used to. Here's an example followed by an explanation:

Generic Code Example:

>>> myjob = "lumberjack" 
>>> for c in myjob: print c,        # step though items 
... 
l u m b e r j a c k 
>>> "k" in myjob                    # 1 means true 
1 

Indexing and slicing strings

Strings in Python are handled similar to arrays in C. Unlike C arrays, characters within a string can be accessed both front and backwards. Frontways, a string starts of with a position of 0 and the character desired is found via an offset value. However, you also can find this character by using a negative offset value from the end of the string. I won't go deeply into it, but here's a quick example:

Generic Code Example:

>>>S = "spam"
>>>S[0], S[-2]
('s', 'a')

Slicing a string is basically what it sounds like: by giving upper and lower index values, we can pull out just the characters we want. A great example of this is when processing an input file where each line is terminated with a newline character; just slice off the last character and process each line. You could also use it to process command-line arguments by "filtering" out the program name. Again, here's an example:

Generic Code Example:

>>> S[1:3], S[1:], S[:-1]     # slicing: extract section 
('pa', 'pam', 'spa')

Python supports the same % operator that C's sprintf function does. You can process a string the same way as in C if you choose to, such as %d for integers and %f for floating point numbers. It also has a string utility module for tools such as case conversion, converting strings to numbers, etc. Here's yet another example:

Generic Code Example:

>>> import string              # standard utilities module 
>>> S = "spammify" 
>>> string.upper(s)            # convert to uppercase 
'SPAMMIFY' 
>>> string.find(S, "mm")       # return index of substring 
3 
>>> string.atoi("42"), `42`    # convert from/to string 
(42, '42') 
>>> string.join(string.split(S, "mm"), "XX")
'spaXXify'

I'll leave the last example above as a mental test. If you're really confused, I'll post the answer in the forums. Also notice the example of the last. Backquotes are used to convert an object into a string. This is one way around the don't mix strings and numbers error from earlier.

For a final fling, I'll post an example of a triple-quoted block since there was some confusion on it after another tutorial.

Generic Code Example:

>>> big = """This is 
... a multi-line block 
... of text; Python puts 
... an end-of-line 
marker 
... after each line. """ 
>>> 
>>> big 
'This is\012a multi-line block\012of text; Python puts\012an end-of-line marker\012after each line.'

Note that the \012 is the octal version of \n.

That's it for this tutorial. Hope you like it and possibly learned something. Next time I'll discuss lists, dictionaries, and tuples. They're all similar to each other, so it shouldn't be too difficult to learn. They are very powerful and make a programmer's life much easier. Until next time...

Would you like to comment? This story has been viewed 74,363 times.
« Programming Techniques Colonial Marines RPG has moved! »

__top__

Copyright © GIDNetwork™ 2001 - 2024

Another website by J de Silva

Page generated in : 0.00936 sec.