Tuesday 28 July 2015

Strings 2

#!/usr/bin/env python

# Python has an unhealthy string obsession. There are many ways of converting
# and formatting strings.

A = "hello world"

# More formatting.
# https://docs.python.org/2.7/library/string.html#string-formatting
print "The first character of A is %s." % A[0] # Old method.
print "The first character of A is {!s}.".format(A[0]) # New method, Python 3.

# Some useful built in string methods.
# https://docs.python.org/2.7/library/stdtypes.html#string-methods

# Check and convert a string to all caps.
print(str.upper(A))

if str.isupper(A):
        print(A)
else:
        print(str.upper(A) + " : Converted with str.upper().")
        print(str.swapcase(A) + " : Converted with str.swapcase().")
        print(A + " : Original remains intact. Strings are immutable!")

# Check and convert a string to all lower case.
B = "HELLO WORLD"
print(str.lower(B))

if str.islower(B):
        print(B)
else:
        print(str.upper(B) + " : Converted with str.lower().")
        print(str.swapcase(B) + " : Converted with str.swapcase().")
        print(B + " : Original remains intact. Strings are immutable!")

# Be careful with str.swapcase()
print(str.swapcase("str.swapcase Literally swAps eACH CHARACTER'S case."))

# Capitalise the first letter only.
print(str.capitalize(A))
print(str.capitalize(B))

# Find a substring within a string.
stringToFind = "lo"
i = A.find(stringToFind)
print(A[i:i + len(stringToFind)] + " found at position %d") % i

# The last example uses a technique called slicing with the print statment.
# This is used to print a sub string and can infact be used on most list
# style objects with indices. The axample below is a bit simpler.

print(A[0:5])

# The first value in the square brackets is the index position to begin at.
# The second value is the number of positions we want to include in the slice.
# It is NOT an index value.

# So if we imagine our string "Hello World" is a row of boxes. What we're
# telling Python to do is start at index 0 and print only the next 5 boxes.
# The index value for the "o" in "Hello" will of course be 4 and not 5. This is
# because the indices in lists and strings begin at 0 and not 1.

No comments:

Post a Comment