14. Revenge of the Strings

And now presenting a cool trick that can be done with strings:

def shout(string):
    for character in string:
        print "Gimme a "+character
        print "'"+character+"'"

shout("Lose")

def middle(string):
    print "The middle character is:",string[len(string)/2]

middle("abcdefg")
middle("The Python Programming Language")
middle("Atlanta")

And the output is:

Gimme a L
'L'
Gimme a o
'o'
Gimme a s
's'
Gimme a e
'e'
The middle character is: d
The middle character is: r
The middle character is: a
What these programs demonstrate is that strings are similar to lists in several ways. The shout procedure shows that for loops can be used with strings just as they can be used with lists. The middle procedure shows that that strings can also use the len function and array indexes and slices. Most list features work on strings as well.

The next feature demonstrates some string specific features:

def to_upper(string):
    ## Converts a string to upper case
    upper_case = ""
    for character in string:
        if 'a' <= character <= 'z':
            location = ord(character) - ord('a')
            new_ascii = location + ord('A')
            character = chr(new_ascii)
        upper_case = upper_case + character
    return upper_case

print to_upper("This is Text")
with the output being:
THIS IS TEXT
This works because the computer represents the characters of a string as numbers from 0 to 255. Python has a function called ord (short for ordinal) that returns a character as a number. There is also a corresponding function called chr that converts a number into a character. With this in mind the program should start to be clear. The first detail is the line: if 'a' <= character <= 'z': which checks to see if a letter is lower case. If it is than the next lines are used. First it is converted into a location so that a=0,b=1,c=2 and so on with the line: location = ord(character) - ord('a'). Next the new value is found with new_ascii = location + ord('A'). This value is converted back to a character that is now upper case.

Now for a shorter typing exercise:

print "Integer to String"
print repr(2)
print repr(23445)
print repr(-23445)
print "String to Integer"
print int("14234")
print int("12345")
print int("-3512")
print "Float to String"
print repr(234.423)
print repr(62.562)
print repr(-134.5660)
print "Float to Integer"
print int(51.523)
print int(224.63)
print int(-1234.562)

The familiar looking output is:

Integer to String
2
23445
-23445
String to Integer
14234
12345
-3512
Float to String
234.423
62.562
-134.566
Float to Integer
51
224
-1234

If you haven't guessed already the function repr can convert a integer to a string and the function int can convert a string to an integer. The repr function returns a printable representation of something. Here are some examples of this:

>>> repr(1)
'1'
>>> repr(234.14)
'234.14'
>>> repr([4,42,10])
'[4, 42, 10]'
The int function tries to convert a string (or a float) into a integer. There is also a similar function called float that will convert a integer or a string into a float. Another function that Python has is the eval function. The eval function takes a string and returns data of the type that python thinks it found. For example:
>>> v=eval('123')
>>> print v,type(v)
123 <type 'int'>
>>> v=eval('645.123')
>>> print v,type(v)
645.123 <type 'float'>
>>> v=eval('[1,2,3]')
>>> print v,type(v)
[1, 2, 3] <type 'list'>
If you use the eval function you should check that it returns the type that you expect.

One useful string function is the split function. Here's the example:

>>> import string
>>> string.split("This is a bunch of words")
['This', 'is', 'a', 'bunch', 'of', 'words']
>>> string.split("First batch, second batch, third, fourth",",")
['First batch', ' second batch', ' third', ' fourth']
Notice how split converts a string into a list of strings. The string is split by spaces by default or by the optional second argument (in this case a comma).


Subsections