字符串、组合数据类型练习

一、字符串练习:

1.http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1027/8443.html

取得校园新闻的编号

 

url="http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1027/8443.html"
print(url[-14:-5])

 

2.https://docs.python.org/3/library/turtle.html

产生python文档的网址

 

abbr1='http://news.gzcc.cn/html/xiaoyuanxinwen/4'
abbr2='.html'
print(abbr1+abbr2)

 

 3.http://news.gzcc.cn/html/xiaoyuanxinwen/4.html

产生校园新闻的一系列新闻页网址

 

for i in range(1,231):
    abbr="http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html".format(i)
    print(abbr)

 

4.练习字符串内建函数:strip,lstrip,rstrip,split,count

(1)用函数得到校园新闻编号

 

str="http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1027/8443.html"
print(str.split("_",-2)[1].rstrip(".html"))

 

(2)用函数统计一歌词中单词出现的次数

 

str="Time goes by so fast, people go in and out of your life. You must never miss the opportunity to tell these people how much they mean to you."
print(str.count("you"))

 

(3)将字符串分解成一个个的单词

str="Time goes by so fast, people go in and out of your life. You must never miss the opportunity to tell these people how much they mean to you."
print(str.split())

二、组合数据类型练习

分别定义字符串,列表,元组,字典,集合,并进行遍历。

1.定义字符串,并进行遍历

str="China"
for i in str:
    print(i)

 

2.定义列表,并进行遍历

a= ['a','b','c','d','e','f']
for i in a:
    print(i)

3.定义元祖,并进行遍历

tup= ('physics', 'chemistry', 1997, 2000);
for i in range(len(tup)):
    print(tup[i])

4.定义字典,并进行遍历

d = {'a':1,'b':2,'c':3,'d':4}

for k,v in d.items():
    print(k,v)

5.定义集合,并进行遍历

st = set([1,2,'a','c',4,'d'])
for i in st :
    print(i)

三、总结列表,元组,字典,集合的联系与区别。

 

1)列表是任意对象的序列。列表用方括号表示。

 

2)将一组值打包到一个对象中,称为元组。元组用圆括号表示。元组和列表的大部分操作相同。但是,列表是不固定的,可以随时插入,删除;而元组一旦确认就不能够再更改。所以,系统为了列表的灵活性,就需要牺牲掉一些内存;而元组就更为紧凑。

 

3)与列表和元组不同,集合是无序的,也不能通过索引进行访问。此外,集合中的元素不能重复。

 

4)字典就是一个关联数组或散列表,其中包含通过关键字索引的对象。用大括号表示。与集合相比,通过关键字索引,所以比集合访问方便。字典是Python解释器中最完善的数据类型。

 

 

 

 

 

 

 

 

posted @ 2018-03-21 20:03  146-王星宇  阅读(142)  评论(0编辑  收藏  举报