Python Level 2 Weekly Exercises 18

Exercise 1:

Enter any string from the keyboard and separate the characters in the string according to the following requirements:
1. Take out the even-numbered elements of the string respectively (note: the position of the string is determined by counting from left to right)
2 , and store them in a list in turn;
3. Output this list.

Answer:

n=input('请输入任意字符串:')   #创建变量n存放用户输入内容
list1=[]                    #创建变量list1为空列表
for i in range(len(n)):     #len()获取字符串长度 使用range()函数配合for进行循环
    if i %2==0:             #判断是否为第偶数位的元素
       list1.append(n[i])   #符合条件的 使用append函数插入空列表list1
else:                       #for循环结束
    print(list1)            #打印出list1 列表

Exercise 2:

Write a program to help teachers classify English letters, numbers and other characters (note: including spaces) in English test papers and count the number of each character.
Input sample:
* Welcome to 2023~!
Output sample:
Letters: Welcometo, 9 in total
Numbers: 2023, 4 in total
Other characters:
~! 6 in total

Answer:

str1=input('请输入任意字符串:') #创建变量str1存放用户输入内容
#str1='**Welcome to 2023~!'  #创建变量str1存放字符串 **Welcome to 2023~!
z=''                         #创建变量z存放字母字符串 初始化为空
s=''                         #创建变量s存放数字字符串 初始化为空
q=''                         #创建变量q存放其他字符串 初始化为空
for i in str1:               #使用for循环 遍历str1字符串每一项目
    if 65<=ord(i)<=90 or 97<=ord(i)<=122:  #根据下图ASCII码 发现字母从A~Z的ASCII值65~90之间 a~z的ASCII值97~122之间
        z+=i                        #符合条件的添加到字符串z里面
    elif ord(i)>=48 and ord(i)<=57: #根据下图ASCII码 发现字母从0~9的ASCII值48~57之间
        s+=i                        #符合条件的添加到字符串s里面
    else:                           #排除以上情况
        q+=i                        #符合条件的添加到字符串q里面
print('字母: %s,共%d个'% (z,len(z)))
print('数字: %s,共%d个'% (s,len(s)))
print('其它字符: %s,共%d个'% (q,len(q)))

ASCII comparison table
Insert image description here

If you feel that you have gained something, you are welcome to give me a reward———— to encourage me to output more high-quality contentInsert image description here

Guess you like

Origin blog.csdn.net/weixin_40762926/article/details/132853484