Keywords: easytut

Next: File IO Up: Non-Programmers Tutorial For Python Previous: More on Lists Contents
Subsections

- Examples

# 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 some interactive typing exercise:

    >>> #Integer to String
    ...
    >>> 2
    2
    >>> repr(2)
    '2'
    >>> -123
    -123
    >>> repr(-123)
    '-123'
    >>> #String to Integer
    ...
    >>> "23"
    '23'
    >>> int("23")
    23
    >>> "23"*2
    '2323'
    >>> int("23")*2
    46
    >>> #Float to String
    ...
    >>> 1.23
    1.23
    >>> repr(1.23)
    '1.23'
    >>> #Float to Integer
    ...
    >>> 1.23
    1.23
    >>> int(1.23)
    1
    >>> int(-1.23)
    -1
    >>> #String to Float
    ...
    >>> float("1.23")
    1.23
    >>> "1.23"
    '1.23'
    >>> float("123")
    123.0

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 function `float` can convert a string to a float. 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).

# Examples

    #This program requires a excellent understanding of decimal numbers
    def to_string(in_int):
        "Converts an integer to a string"
        out_str = ""
        prefix = ""
        if in_int < 0:
            prefix = "-"
            in_int = -in_int
        while in_int / 10 != 0:
            out_str = chr(ord('0')+in_int % 10) + out_str
            in_int = in_int / 10
        out_str = chr(ord('0')+in_int % 10) + out_str
        return prefix + out_str

    def to_int(in_str):
        "Converts a string to an integer"
        out_num = 0
        if in_str[0] == "-":
            multiplier = -1
            in_str = in_str[1:]
        else:
            multiplier = 1
        for x in range(0,len(in_str)):
            out_num = out_num * 10 + ord(in_str[x]) - ord('0')
        return out_num * multiplier

    print to_string(2)
    print to_string(23445)
    print to_string(-23445)
    print to_int("14234")
    print to_int("12345")
    print to_int("-3512")

The output is:

    2
    23445
    -23445
    14234
    12345
    -3512

Next: File IO Up: Non-Programmers Tutorial For Python Previous: More on Lists Contents