PY4E - Chapter 6练习题|len & find语句|个人向分享

Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards.

fruit = 'banana'
index = -1
while -index <= len(fruit):
    letter = fruit[index]
    print(letter)
    index = index - 1

运行结果:

a
n
a
n
a
b

Exercise 3: Encapsulate this letter-counting code in a function named count, and generalize it so that it accepts the string and the letter as arguments.​​​​​​​

def letter_count():
    count = 0
    word = input('Please enter a word')
    letter = input('Please enter the letter that you want to count')
    for letters in word:
        if letters == letter:
            count = count + 1
    print(word, letter, count)
    
letter_count()

运行结果:

Please enter a word aabbcc
Please enter the letter that you want to count a
aabbcc a 2
Please enter a word 112234
Please enter the letter that you want to count 2
112234 2 2

Exercise 4: There is a string method called count that is similar to the function in the previous exercise. Read the documentation of this method at:

Built-in Types — Python 3.11.5 documentation

Write an invocation that counts the number of times the letter a occurs in “banana”.

word = 'banana'
word.count('a')

3​​​​​​​

写了一个输入版本:

def word_count():
    word = input('Please enter a word')
    word = '%s' % word
    letter = input('Please enter the letter you want to count')    
    num = word.count('%s' % letter)
    return num

word_count()

Exercise 5: Take the following Python code that stores a string:

str = 'X-DSPAM-Confidence:0.8475'

Use find and string slicing to extract the portion of the string after the colon character and then use the float function to convert the extracted string into a floating point number.

string = 'X-DSPAM-Confidence:0.8475'
num1 = string.find(':')
num2 = string.find(' ', num1)
x = string[num1+1:num2]
print(x)

个人练习记录,欢迎一起讨论~

如需转载请联系作者并注明出处。

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值