python作业2-7答案_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

2.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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值