Preview

12 - String Manipulation

 1. If you want to slice off unwanted parts of a string from the beginning or end you can do so by creating a substring. The following code will produce an output of:
message9 = "Hello World"
message9a = message9[1:8]
print(message9a)
stringmanipulation_python_question_1.jpg

  ello Wo

  Hello

  World

  llo Worl

 2. Note here that we are using the escape character "/" ...the output here is:
>>> spam = 'it\'s only a bunny'
>>> print(spam[0:5])

  it's

  its

  \

  ERROR

 3. Can you name one benefit of converting user input into lower?
spam = input('What is your favorite colour?').lower()

  makes checking or validating the input easier as you do not need to worry about the case

  makes adding up any input easier, as lower case strings convert easily to numbers

  There are no benefits.

  makes it easier to read, as lower case is much easier on the eyes than upper

 4. The ord function gives the ______ value of a character. The chr function returns an integer into ______
>>> ord('b')

98

>>> chr(13)

\r

  index / string

  whole / integer

  integer / ascii

  ascii / integer

 5. The use of the + operator on line 3 is joining together strings to output: _____________ on line 4. This is called ___________________.
firstname="Joe"
lastname="Bloggs"
fullname=firstname+lastname
print(fullname)

  Joe Bloggs / concatenation

  JoeBloggs / concatenation

  JoeBloggs / combination

  Joe Bloggs / addition

 6. You can also perform logical tests on strings using "in" and "not". Fill in the blanks below.
>>> 'spam' in 'spam and eggs'

___________?

>>> 'gord' in 'brave sir Robin'

___________?

  False / False

  False / True

  True / False

  True / True

 7. What is the output when following code is executed ?
>>> str1 = 'hello'
>>> str2 = ','
>>> str3 = 'world'
>>> str1[-1:]

  h because -1 refers to the first index from the left

  error - you cannot use a minus

  l - because -1 takes last letter -1 from the right.

  o because -1 corresponds to the last index.

 8. Given that the string variable order = "lobster", what would the value of order.subString(2,3) be?

  bst

  lob

  ter

  bs

 9. Landrover has brought out a new discovery sport model and its launch_date is: 8 January 2019. (see below) State the output for the following - fill in the blanks.
launch_date="8 Jan 2019"

launch_date.subString[0]+date.subString(10,4)

>>Output 1 _______________?

launch_date.subString(2,3).upper

>>Output 2 _______________?

  Output 1: 27; Output 2: jAN

  Output 1: 82019; Output 2: JAN

  Output 1: 98201; Output 2: JAN

  Output 1: 27; Output 2: jan

 10. What will the output of the following code be?
def main():

    string="I love python programming because python is fun, yes python is fun"
    
    number_of_pythons_in_string=string.count("python")
    print(number_of_pythons_in_string)
    
main()

  1

  3

  Error

  2