STRINGS

Throughout the course, you’ve seen me refer to strings … variables declared like this:

[python]
school = "Merivale" #school is a string
name = input("Please enter your name: ") #name will be a string by default
[/python]

It’s time to start thinking about what we can do with strings. We should start by NOT thinking about it like a variable but rather as a list of individual characters. In Python, strings are objects.

Have a look at the image at the top of the page. Strings can be treated like lists, meaning we can get substrings (slicing), access individual indexes, and much more. The only difference is that STRINGS ARE NOT MUTABLE. This means that you cannot change a character at a given index. Have a look at the sample code below to find out more.

[python]
school = "Merivale"

print (school)
#Output Merivale

print (school[0])
#Output M

print (school[1:4])
#Output eri

school[0] = ‘m’
#TypeError: ‘str’ object does not support item assignment
#You cannot change an element in a string like you can in a regular list
[/python]

Ok, so if a string is like a list but we can’t manipulate the elements then what is the point? Great question. Strings come with a library of methods (functoins) that allows us to perform some checks and changes to the variable.

Below you will find some functions from the string library that may interest you. Just be aware that most of these functions are being used in their simplest form, and optional parameters are not being used. For instance, you can use the print() function in a few different ways.

[python]
print("Hello")
print("Hello", end="*") #Added an extra parameter to tell the program how I wanted the line to end.
[/python]

Please read the documentation before you reinvent the wheel.

Sample Code

Copy the code below and paste it into the interpreter. Have a look at the results and see your teacher if you have any difficulties. Try changing some of the values to see what effect it will have on the output.

In the following examples, the result from the output of the string function is sent to print() so that you can see it.

[python]
# Build strings for later use
mystr = ‘abcbdefghija’
mynum = ‘1234’
mytitle = ‘This Is My Title’
dot = ‘.’
letters = (‘A’, ‘B’, ‘C’)
mess = ‘ asdasdas dd ‘
intab = "aeiou"
outtab = "12345"
str = "this is string example….wow!!!"
messy = ‘Change The Case’
commaland = ‘a,b,c,d,e,f’

print(mystr.capitalize()) # Capitalize first character

print(mystr.center(20, ‘$’)) # Centre text. Pad with provided text

print(mystr.count(‘a’)) # Count occurrences of a substring

print(mystr.endswith(‘ija’)) # Check suffix (ending), return Boolean

print(mystr.find(‘b’)) # Find and return first occurrence of substring, if substring not found return -1

’12’ in ‘1234’ # Use instead of find() to verify the substring

print(mynum.isalnum()) # Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise.

print(mystr.isalpha()) # Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

print(mynum.isdigit()) # Return true if all characters in the string are digits and there is at least one character, false otherwise.

print(mytitle.istitle()) # Return true if the string is a titlecased string and there is at least one character, false otherwise.

print(mytitle.isupper()) # Return true if all cased characters in the string are uppercase and there is at least one cased character,
# false otherwise.

print(dot.join(letters)) # Return a string, which is the concatenation of the strings in the sequence.

print(mytitle.lower()) # Return a copy of the string with all the cased characters converted to lowercase.

print(mess.lstrip()) # Return a copy of the string with leading characters removed.
# The chars argument is a string specifying the set of characters to be removed.
# If omitted or None, the chars argument defaults to removing whitespace.
# The chars argument is not a prefix; rather, all combinations of its values are stripped

# maketrans() links the translation table (links), translate() applies the table

print(str.translate(str.maketrans(intab, outtab)))

print(mystr.replace(‘a’,’Q’)) # Return a copy of the string with the substrings replaced

print(mystr.rfind(‘b’)) # Find and return last occurrence of substring, if substring not found return -1

print(mess.rstrip()) # Return a copy of the string with trailing characters removed.
# The chars argument is a string specifying the set of characters to be removed.
# If omitted or None, the chars argument defaults to removing whitespace.
# The chars argument is not a prefix; rather, all combinations of its values are stripped

print(commaland.split(‘,’)) # Return a list of the words in the string. With or without delimiter string

print(mystr.startswith(‘abc’)) # Check prefix (beginning), return Boolean

print(mystr.strip(‘ab’)) # Return a copy of the string with the leading and trailing characters removed

print(messy.swapcase()) # Return a copy of the string with uppercase characters converted to lowercase and vice versa.

print(str.title()) # Return a titlecased version of the string where words start with an uppercase character
# and the remaining characters are lowercase.

print(str.upper()) # Return a copy of the string with all the cased characters converted to uppercase.

# FUN STRING STUFF NOT DIRECTLY PART OF THE STRING LIBRARY

print(len(mystr)) # len() returns the length of an object. Strings in Python are objects. Not a String
# library function. Standard Python Library.

print(‘*’ * 10) # use the multiply operator for printing repeated characters

print (messy + mystr) # use the concatenation operator for joining two strings

print(":".join(mystr)) # provide join() a sequence and separate it with the string

# calling join. In this case

# a ‘:’ string called join()
[/python]

Check Your Understanding

Before moving to the next section, let’s see how well you know the current material.

  1. Create the program that will search a string for a substring. If found, give it’s location (index).
  2. Create the program that will convert a sentence to title case.
  3. Create the program that will concatenate two words entered by the user to a new variable and then print that variable
  4. Create the program that will allow the user to enter a string and will print an asterix (*) for each letter. eg. If they enter “Merivale”, your program should output ********.