Preview

10 - String Manipulation #1

 1. Strings are everywhere and are crucial in programming. A string in python is:
Note: the following embedded powerpoint from www.teachyourselfpython.com provides a comprehensive overview on all you need to know on strings and string manipulation

  A sequence of characters. E.g. "Jonathan" or "ABC123"

  A type of array that stores only text

  A type of variable in which whole numbers are stored

  A piece of invisible thread that holds the code together

 2. There are several python methods that _____ strings such as replace(), join(), split().

  delete

  obliterate

  modify

  find

 3. In the following code, the output is 'M' and then 'Mr', what would you need to produce an output of 'Moo'?
string="Mr Moose"
print(string[0])
print(string[0:2])

  print(string[2:5])

  print(string[3:5])

  print(string[2:6])

  print(string[3:6])

 4. What will the following produce
string="Mr Moose"
print(len(string))

  6

  7

  5

  8

 5. What is this code doing?
word="Hello World"
print word.index("World") 

  None of the above

  It is finding the index position (6) of the word 'World' in the string 'word'

  It is finding the index position of the letter 'W' (5) in the word 'World'

  It is finding the count of the length of the word 'World' which is 5

 6. Splitting and stripping strings is extremely useful - especially when working with files.

  False

  True

 7. What is the output of the following code?
word="Hello World"

print(word.startswith("H"))
print(word.startswith("W"))

  False, False

  True, True

  True, False

  False, True

 8. The "in" and "not in" operators are useful tools. What is the output of the following?
word="Hello World"
print('cats' not in word)
print('Hello' in word)

  False, False

  True, True

  True, False

  False, True

 9. If you enter 'GREAT' (in capitals) to the following program, what will the output be?
print('How are you?')
feeling = input()
if feeling.lower() == 'great':
    print('I feel great too.')
else:
    print('I hope the rest of your day is good.')

  I feel great too.

  Error

  I hope the rest of your day is good.

  I feel GREAT too

 10. The following are additional methods that can be used on strings. Read through the excerpt and fill in the first blank.
Along with islower() and isupper(), there are several string methods that have names 
beginning with the word is. These methods return a Boolean value that describes 
the nature of the string. Here are some common isX string methods:

isalpha() returns True if the string _________________________________________________?

isalnum() returns True if the string consists only of letters and numbers and is not blank.

isdecimal() returns True if the string consists only of numeric characters and is not blank.

isspace() returns True if the string consists only of spaces, tabs, and new-lines and is not blank.

istitle() returns True if the string consists only of words that begin with an uppercase 
letter followed by only lowercase letters.

  consists of either a blank value or only letters.

  consists of an integer value only

  is blank and NULL

  consists only of letters and is not blank.

 11. The join() method is useful when you have a list of strings that need to be joined together into a single string value
>>> ', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'

  TRUE

  FALSE

 12. Analyse the following code and select the statement that is correct.
>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']

  A common use of split() is to split a multiline string along the newline characters.

  By default, the string 'My name is Simon' is split wherever whitespace characters such as the space, tab, or newline characters are found.

  The string is split and whitespace characters are not included in the strings in the returned list

  All of the above statements are true

 13. Sometimes you may want to strip off whitespace characters (space, tab, and newline) from the left, right or from both sides of a string. An example is:

  Customers enter their postcode and include different spaces but you wish to store the postcode without any spaces

  Students in a school enter their username with an additional space before the username and cannot login as a result

  If a user enters an accidental space when they enter their password (strip any leading spaces off)

  All of the above statements are true

 14. Fill in the blanks for the following
The strip() string method will return a new string without any whitespace 
characters at the ____________________ The lstrip() and rstrip() methods will 
remove whitespace characters from the left and right ends, respectively

  beginning or end.

  beginning

  middle or centre of the string

  end

 15. Analyse the following program. If the user enters "open 123" (a space in the middle) access is denied. How do you fix this?
#TASK
#a common mistake that students make is to add a space by mistake when entering their password
#create a program that
#asks the user for their password
#if they put in a blank space anywhere, REMOVE IT
#"acecss granted" as long as the password is right without the blank spaces

#The following code removes the trailing and leading white spaces 
#but not the ones in between. Can you fix it?
#Hint: Use "replace" to replace ALL blank spaces in the string
def main():
    password=input("What is your password:?")
    password=password.strip()
    #What goes here?
    if password=="open123":
        print("access granted")
    else:
        print("sorry denied")


main()

  Line 14: password=password.strip("")

  Line 14: password=password.lstrip(" ")

  Line 14: password=password.replace(" ","")

  All of the above could work to remove spaces from the middleof the string input

 16. The following code puts together two strings but there is no space between the "Mr" and "Moose". What needs to be added to line 3?
string1="Mr"
string2="Moose"
fullname=string1+string2
print(fullname)

  fullname=string1+ space +string2

  fullname=string1+ "____" +string2

  fullname=string1+ split("")+string2

  fullname=string1+ " " +string2

 17. _________ is the big word which means to link things together. You can do this with strings with the + operator.
#e.g. "this"+"this">>thisthis

  manipulation

  concatenation

  mutination

  combination

 18. What does the term 'casting' mean? You'll come across it a lot in programming

  int(item) casts the item into an integer and this is an example of casting

  str(item) converts the item into a string and this is casting

  All of the above are valid

  Converting from one data type to another is called casting

 19. When would casting be needed in a program?

  If a string input needs to be treated like an integer so that calculations can be done on it

  None of the above

  if an integer input needs to be converted into a string so that mathematical calculations can be applied to it.

  if a string input needs to be stripped of spaces so it is acceptable

 20. There are plenty of other methods that can be applied to a string including:

  All of the above

  Split a string at a given position into two separate strings

  removing all white space from a string

  extend a string by duplicating itself (7 becomes 7777 etc)