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)
个人练习记录,欢迎一起讨论~
如需转载请联系作者并注明出处。