full-speed-python 习题解答(二)

本文深入探讨Python中字符串和列表的基本操作,包括初始化、查找、替换、切片及平均值计算等,通过实例演示如何高效处理数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目地址:网页地址
full-speed-python书籍地址:https://github.com/joaoventura/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]

参考链接:https://www.chzzz.club/post/12.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值