Tuesday 28 July 2015

Strings 1

#!/usr/bin/env python

# The first thing to note about strings is that they are basically lists of
# characters. This means all elements of a string can be accessed directly
# using their indices.

# Python strings effectively have two indices. The first starts at 0 for the
# first character on wards. The second starts at -1 from the last character.

A = "Hello World"
print "The first character of A is \"%s\"." % A[0]
print "The last charachter of A is \"%s\"." % A[-1]

# The code above looks very simple. And it is. However a number of thing are
# happening that would normally require a lot more code in Java or C.

# 1. A is declaired and it's value set as the string "Hello World".
# 2. Python is told to print the first and last characters.
# 3. ASCII escape characters are used to enclose the first and last characters
#    in double quotes. Getting to grips with these will save a lot of code.
# 4. We perform a substitution instead of concatinating multiple strings.

# Concatinated version.
print ('The first character of A is ' + '"' + A[0] + '".')
print ('The first character of A is ' + '"' + A[-1] + '".')

# Slightly more complex examples.
B = ["first","second","third","fourth","last","second last"]
print ("The %s character of A is \"%s\".") % (B[0],A[0])
print ("The %s character of A is \"%s\".") % (B[1],A[1])
print ("The %s character of A is \"%s\".") % (B[4],A[-1])
print ("The %s character of A is \"%s\".") % (B[5],A[-2])

print ('The ' + B[0] + ' character of A is ' + '"' + A[0] + '".')
print ('The ' + B[1] + ' character of A is ' + '"' + A[1] + '".')
print ('The ' + B[4] + ' character of A is ' + '"' + A[-1] + '".')
print ('The ' + B[5] + ' character of A is ' + '"' + A[-2] + '".')

# Integer substition example.
print ("The %s character of A is \"%s\". A is %d characters long.") % (B[4],
        A[-2],len(A))
       
print ('The ' + B[4] + ' character of A is ' + '"' + A[-1] + '". A is '
        + str(len(A)) + ' characters long.')

# Note that to substitute in an integer %d is used instead of %s. Conversion of
# the integer happens automatically. However in the concatination version the
# conversion must be done manually. Which isn't a problem in this example. But
# it would make larger programs harder to read and maintain.

# More information on string formatting can be found here,
# https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

No comments:

Post a Comment