Python 实验3 复杂数据类型

Python 实验3 复杂数据类型,第1张

实验目的

  1. 巩固掌握Python流程控制语法;
  2. 掌握字符串、元组、列表、字典等类型特点;
  3. 掌握元素添加、删除、查找等 *** 作

实验内容

完成以下程序编写要求并测试:

1. 已知一个字符串中包含了许多组英文单词和中文词,英文和中文交错排列。现需要编程将中文和英文分开,然后分别输出。

分析:对原字符串的每个字符,利用ord函数检查其编码值,在[0,127]范围内即为英文,否则为中文,虽然字符串是不可变的类型,可以转化为可变类型的列表进行处理。

s=input('please input string:(Both English and Chinese are included)')
temp=list(s)
English=[]
Chinese=[]
for i in temp:
    if ord(i)>=0 and ord(i)<=127:
        English.append(i)
    else:
        Chinese.append(i)
print('English:',''.join(English))
print('chinese:',''.join(Chinese))

运行结果

2. 已知输入一个十进制的IP地址,形如***.***.***.***的字符形式,其中***为0~255之间的整数。现需要编程将IP地址转换为32位二进制形式输出,也就是将***转换为8位二进制数后依次输出,如输入16.255.1.8,输出00010000 11111111 00000001 00001000。

 

s=input('please input a decimal IP address(0-255):')
list_1=s.split('.')#分割ip
list_2=[]
for temp in list_1:
    temp= bin(int(temp))#进制转换(srt->d->0b)
    temp=temp[2:]#去除前面二进制标志(0b)
    list_2.append('{0:>08}'.format(temp))#统一格式
    s1=' '.join(list_2)#使用空格将列表连接成字符串
print('二进制IP为:',s1)

运行结果

3.编写一段程序,可以输入两个字符串,输出从第一个字符串中删除第二个字符串中所有字符的结果。例如,输入“They are student.”和“aeiou”,则删除之后的第一子字符串变成“Thy r stdnts.”。

 

s_1 = input('Please enter the first string:')
s_2 = input('Please enter the second string:')
list_1 = list(s_1)
list_2 = list(s_2)
for i in list_1:
    for j in list_2:
        if i == j:
            list_1.remove(i)
print(''.join(list_1))

运行结果

4. 编写一段程序,用于统计输入字符串中每个字母的出现次数(忽略大小写,如a与A算同一个字母),要求结果以字典类型保存,如{‘a’:3,’b’:1}。

 

s_1 = input('please input a string:').lower()
result= {}
for i in s_1:
    result[i] = s_1.count(i)
print(result)

运行结果

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/801134.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-07
下一篇 2022-05-07

发表评论

登录后才能评论

评论列表(0条)

保存