1. 程式人生 > >full-speed-python 習題解答(二)

full-speed-python 習題解答(二)

3.2 Exercise with strings 1.Initialize the string “abc” on a variable named “s”: (a) Use a function to get the length of the string. (b) Write the necessary sequence of operations to transform the string “abc” in “aaabbbccc”. Suggestion: Use string concatenation and string indexes.

  s='abc'
  print(len(s))
  print('{0}{0}{0}{1}{1}{1}{2}{2}{2}'.format('a','b','c'))
  print(s[0]*3+s[1]*3+s[2]*3)

3 aaabbbccc aaabbbccc

  1. Initialize the string “aaabbbccc” on a variable named “s”: (a) Use a function that allows you to find the first occurence of “b” in the string, and the first occurence of “ccc”. (b) Use a function that allows you to replace all occurences of “a” to “X”, and then use the same function to change only the first occurence of “a” to “X”.

      s='aaabbbccc'
     print(s.find('b'))
     print(s.find('ccc'))
     print(s.find('a'))
     print(s.replace(s[4],'X'))
     print(s.replace('a','X',1))
    

    3 6 0 aaaXXXccc Xaabbbccc

    3.Starting from the string “aaa bbb ccc”, what sequences of operations do you need to arrive at the following strings? You can find the “replace” function. (a) “AAA BBB CCC” (b) “AAA bbb CCC”

     s='aaa bbb ccc'
      s=s.upper()
     print(s)
      print(s.replace('B','b'))
    

    AAA BBB CCC AAA bbb CCC

    3.3 Exercise with lists Create a list named “l” with the following values ([1, 4, 9, 10, 23]). 1.Using list slicing get the sublists [4, 9] and [10, 23]. 2.Append the value 90 to the end of the list “l”. Check the difference between list concatenation and the “append” method. 3.Calculate the average value of all values on the list. You can use the “sum” and “len” functions. 4.Remove the sublist [4, 9].

     l = [1,4,9,10,23]
     print(l[1:3])
     print(l[3:5])
     l+[90]
     print('l concatenation 90 is',l)
     l.append(90)
     print('l append 90 is',l)
     ave = sum(l)/len(l)
     print('average is',ave)
     l.remove(4)
     l.remove(9)
     print('l remove [4,9] is',l)
    

    [4, 9] [10, 23] l concatenation 90 is [1, 4, 9, 10, 23] l append 90 is [1, 4, 9, 10, 23, 90] average is 22.833333333333332 l remove [4,9] is [1, 10, 23, 90]