Python basic day03 homework analysis [5 string questions, 3 list questions, 2 tuple questions]

table of Contents

1. String

Topic 1 [Strengthening training]

Question stem

Training goal

Training tips

Reference plan

Steps

Reference answer

Topic 2 [Strengthening training]

Question stem

Training goal

Training tips

Reference plan

Steps

Reference answer

Topic 3 [Strengthening training]

Question stem

Training goal

Training tips

Reference plan

Steps

Reference answer

Topic 4 [Strengthening training]

Question stem

Training goal

Training tips

Reference plan

Steps

Reference answer

Topic 5 [Strengthening training]

Question stem

Training goal

Training tips

Reference plan

Steps

Reference answer

2. List

Topic 1 [Strengthening training]

Question stem

Training goal

Training tips

Reference plan

Steps

Reference answer

Topic 2 [Strengthening training]

Question stem

Training goal

Training tips

Reference plan

Steps

Reference answer

Topic 3 [Strengthening training]

Question stem

Training goal

Training tips

Reference plan

Steps

Reference answer

3. Tuple

Topic 1 [Strengthening training]

Question stem

Training goal

Training tips

Reference plan

Steps

Reference answer

Topic 2 [Strengthening training]

Question stem

Training goal

Training tips

Reference plan

Steps

Reference answer


1. String

Topic 1 [Strengthening training]

Question stem

If you need to use variables to save the following strings, how do we write the code

Lu Xun said: "I haven't said this sentence"

Training goal

Let students know how to nest strings

Training tips

In python, there are two forms of expression that can be defined as string types. Which two ways are they? Can they be mixed?

Reference plan

Use "" and '' to define the string

Steps

  1. To be included in a string 双引号"", the string can be defined with single quotes

  2. To be included in a string 单引号'', the string can be defined with double quotes

Reference answer

 # 在python中,''可以嵌套在""中,用以表示字符串中的字符串
 words = "鲁迅说:'我没有说过这句话'"
 print(words)
 ​
 # 还可以使用三引号
 words = """鲁迅说:'我没有说过这句话'"""
 print(words)

 

Topic 2 [Strengthening training]

Question stem

Make a simple user information management system: prompt the user to enter the name, age and hobbies in turn, and after the input is completed, the data entered by the user will be displayed at once

Training goal

String declaration string input string output

Training tips

  1. In python, declare a variable of string type by "" or"

  2. Use the input() function to get data from the keyboard

  3. Output string type through %s formatting operator

Reference plan

  1. Enter string data through the input function

  2. Use string type to save the entered data

  3. Use %s to format and output the saved data

Steps

  1. Enter string data through the input function

  2. Use string type to save the entered data

  3. Use %s to format and output the saved data

Reference answer

 # 录入数据,并保存在变量中
 name = input("请输入姓名:")
 age = input("请输入年龄:")
 hobby = input("请输入您的爱好:")
 ​
 # 格式化输出数据
 print("您的姓名是%s, 您的年龄是%s, 您的爱好是%s" % (name, age, hobby))
 # 使用 f-string
 print(f"您的姓名是{name}, 您的年龄是{age}, 您的爱好是{hobby}")
 ​

 

Topic 3 [Strengthening training]

Question stem

The existing strings are as follows, please use slices to extract ceg words = "abcdefghi"

Training goal

Use of slicing strings

Training tips

1. The slicing syntax: [start:end:step] 2. The selected interval starts from the "start" bit and ends at the bit before the "end" bit (not including the end bit itself), 3. Step length Indicates the selection interval, the default step size is positive, that is, select from left to right, if the step size is negative, select from right to left

Reference plan

1. Use slice to intercept, start position is -7, end position is -1 2, reverse selection, step size is 2

Steps

  1. The start position is -7, the end position is -1, and the step size is 2

Reference answer

 a = "abcdefghi"
 ​
 b = a[-7:-1:2]
 print(b)

 

Topic 4 [Strengthening training]

Question stem

James has a project about crawlers. He needs to search for the keyword python in a string. Currently he searches through the index() function. Although it can meet the search requirements, he will always report an error when the keyword is not found. , Why is there an error and how to optimize?

Training goal

  1. Understand the difference between find function and index function

Training tips

  1. The find function returns the index value if it is found, or -1 if it is not found

  2. The index function returns the index value if it is found, and reports an error if it cannot be found

Reference plan

  1. Replace index by using the find function

Steps

  1. Replace index by using the find function

Reference answer

 只需要使用find函数替换掉index函数即可,在功能上, find函数index函数完全一致,不同的是index函数在没有查找到关键字的情况下会报ValueError的异常,因此在一般开发环境下通常都会使用find函数

 

Topic 5 [Strengthening training]

Question stem

1. Determine whether the word great is in the string words. If it is, add an s after each great. If it is not, output that great is not in the string. 2. Change every word in the entire string to lowercase. And make the first letter of each word into capital 3, remove the blank at the beginning and end, and output the processed string

 words = " great craTes Create great craters, But great craters Create great craters "

 

Training goal

  1. String related operations

Training tips

  1. String related operations to solve the above problems

  2. Use judgment sentences to judge the conditions for the validity

Reference plan

  1. Use in to determine whether a certain substring is in the parent string

  2. Use the replace function to replace the substring

  3. Use the lower function to change the string to lowercase

  4. Use the title function to capitalize the first letter of a word

  5. Use the strip function to remove whitespace at the beginning and end of a string

Steps

  1. Use in to determine whether a certain substring is in the parent string

  2. Use the replace function to replace the substring

  3. Use the lower function to change the string to lowercase

  4. Use the title function to capitalize the first letter of a word

  5. Use the strip function to remove whitespace at the beginning and end of a string

Reference answer

words = " great craTes Create great craters, But great craters Create great craters "

# 判断单词great是否在这个字符串中
if 'great' in words:
	# 将每一个great替换成greats
    words = words.replace("great", "greats")

    # 将单词变成小写
    words = words.lower()

    # 将每一个单词的首字母都大写
    words = words.title()

    # 去除首尾的空白
    words = words.strip()

    # 最后进行输出
    print(words)

else:
    print("great不在该字符串中")

2. List

Topic 1 [Strengthening training]

Question stem

There is a list, judge whether each element in the list ends with s or e, if it is, put it into a new list, and finally output the new list

 list = ["red", "apples", "orange", "pink", "bananas", "blue", "black", "white"]

Training goal

Let students know the loop and value acquisition of the list, as well as the operation method of the list

Training tips

  1. How to find every element in the list?

  2. How to determine what character the elements in the list end with?

Reference plan

  1. Use a loop to get every element in the list?

  2. The elements in the list are strings, so you can use the subscript [-1] to get the value of the last character, and then judge.

 

Steps

  1. Traverse each element in the list

  2. if determines whether the last character is sore

  3. If it is, use the append() method to append the data to the new list.

 

Reference answer

 my_list = ["red", "apples", "orange", "pink", "bananas", "blue", "black", "white"]
 ​
 # 用来存放以e或者s结尾的字符串
 new_list = []
 ​
 for i in my_list:
     # 判断列表中每一个元素是否以s或e结尾
     if i[-1] == 's' or i[-1] == 'e':
         new_list.append(i)
 ​
 # 打印出这个新的列表
 print(new_list)

Method Two:

Use the method in the string to judge.

 my_list = ["red", "apples", "orange", "pink", "bananas", "blue", "black", "white"]
 ​
 # 用来存放以e或者s结尾的字符串
 new_list = []
 ​
 for i in my_list:
     # 判断列表中每一个元素是否以s或e结尾
     if i.endswith('s') or i.endswith('e'):
         new_list.append(i)
 ​
 # 打印出这个新的列表
 print(new_list)
 ​

 

 

Topic 2 [Strengthening training]

Question stem

Given a list, first delete the element starting with s, after deleting, modify the first element to "joke", and make a copy of the last element and place it after joke

 my_list = ["spring", "look", "strange", "curious", "black", "hope"]

Training goal

List related operations

Training tips

  1. Traverse the list through the for loop to get each element

  2. Modify the list through the operation method of the list

Reference plan

  1. Get each element through the for loop

  2. Remove the elements in the list by remove

  3. Insert an element at the specified position through the insert function

Steps

  1. Get each element through the for loop to determine whether it sstarts with

  2. If the condition is true, delete the selected element through remove

  3. Get the last element, place the element at the specified position by replace

Reference answer

 my_list = ["spring", "look", "strange" "curious", "black", "hope"]
 ​
 for i in my_list[:]:
     # 删除以s开头的元素,
     if i[0] == 's':
         my_list.remove(i)
 ​
 # 修改第一个元素为"joke"
 my_list[0] = "joker"
 ​
 # 获取最后一个元素
 last_one = my_list[-1]
 ​
 # 将最后一个元素放在joke的后面
 my_list.insert(1, last_one)
 ​
 print(my_list)

 

Topic 3 [Strengthening training]

Question stem

Combine the following two lists, de-duplicate the combined list, and output in descending order

 list1 = [11,  4, 45, 34, 51, 90]
 list2 = [4, 16, 23, 51, 0]

 

Training goal

Use of List Operation Method

Training tips

  1. How to merge two lists?

  2. How to remove duplicate lists?

  3. How to sort and output in descending order?

 

Reference plan

  1. To merge lists, you can use the extend() method or add two lists.

  2. There are two options for list deduplication

  3. Implement the method yourself, with the help of a new list, loop through the original list to determine whether the element is in the new list, if it is, traverse the next element, if not, add it to the new list.

  4. Use set() to remove duplicates

  5. The sort function can realize sorting, and the parameter reverse=True sorts the list in reverse order

Steps

1. Use + to splice the list (or use extend) 2. List to remove duplicates 3. Use the sort function with parameter reverse=True to sort the list in reverse order

Reference answer

plan 1

 list1 = [11, 4, 45, 34, 51, 90]
 list2 = [4, 16, 23, 51, 0]
 ​
 # 1. 使用 + 合并两个列表
 my_list = list1 + list2
 ​
 # 2. 列表去重
 # 2.1 定义新的空列表保存去重后的数据
 my_list1 = []
 # 2.2 遍历合并后的列表
 for i in my_list:
     # 2.3 判断i 是否在my_list1 中
     if i in my_list1:
         # 2.3.1 如果存在,直接下一次循环
         continue
     else:
         # 2.3.2 将i添加到my_list1 中.
         my_list1.append(i)
 ​
 # 3. 循环结束,得到去重后的列表 my_list1,进行排序
 my_list1.sort(reverse=True)
 ​
 # 4. 输出最后的结果
 print(my_list1)
 ​

 

Option 2 Don't worry about it for now and learn later

Use set, de-duplication,

set is also a container, with automatic de-duplication function (will learn later)

Just need to understand for now.

 list1 = [11, 4, 45, 34, 51, 90]
 list2 = [4, 16, 23, 51, 0]
 ​
 # 列表拼接
 list3 = list1 + list2
 ​
 # 列表去重
 list4 = set(list3)
 list5 = list(list4)
 ​
 # 列表降序输出
 list5.sort(reverse=True)
 ​
 print(list5)

3. Tuple

Topic 1 [Strengthening training]

Question stem

There are two lines of code as follows: tuple1 = (2) tuple2 = (2,) What is the difference between tuple1 and tuple2

Training goal

Define a tuple of elements

Training tips

What can be seen by the naked eye is only a comma difference, so how does he understand it in python?

Reference plan

Use the type() method to distinguish these two variables separately

Steps

Use type(tuple1) to compare with the result of type(tuple12)

Reference answer

 tuple1 = (2)
 tuple2 = (2,)
 print(type(tuple1))
 print(type(tuple2))
 # 对于tuple1 = (2),python解释器会将小括号理解成一个运算符号,那么这时候 返回的值是一个int类型
 # 所以对于只有一个元素的元组来说,要创建一个元组,那么就必须要加逗号

 

Topic 2 [Strengthening training]

Question stem

There is the following code, please answer the question?

 my_tuple = ("itcast", "python", "CPP", 18, 3.14, True)
  1. Use the subscript method to output the elements in the tuple "CPP"

  2. Use for loop to traverse tuples

  3. Use while loop to iterate through tuples

Training goal

  1. Subscript operations on tuples

  2. For loop traversal of tuples

  3. While loop traversal of tuples

Training tips

  1. Does the subscript in python start from 0 or 1?

  2. How to traverse for?

  3. How to traverse while? How to write the condition of while?

Reference plan

  1. The subscript starts from 0, so the subscript of CPP is 2

  2. Use for ... in ...traversal

  3. while loop, requires the use of subscripts, conditions can be determined by means len()implemented

Steps

  1. Use the subscript method to take the value of CPP

  2. for loop traversal

  3. while loop traversal

Reference answer

 my_tuple = ("itcast", "python", "CPP", 18, 3.14, True)
 ​
 # 1. 使用下标的方法,输出元组中的元素 `"CPP"`使用下标的方法,
 result = my_tuple[2]
 print(result)
 ​
 # 2. 使用 for 循环遍历元组
 for i in my_tuple:
     print(i)
 ​
 print("-" * 20)
 ​
 # 3. 使用 while 循环遍历元组
 i = 0
 while i < len(my_tuple):
     print(my_tuple[i])
     i += 1
 ​

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_44949135/article/details/113620031