字符串练习

1.字符串练习:

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

取得校园新闻的编号

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

 

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

产生python文档的网址

addr1 = "https://docs.python.org/3/library/"
addr2 = ".html"
addr3 = addr1 + "turtle" + addr2
print(addr3)

 

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

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

addr1 = "https://docs.python.org/3/library/"
addr2 = ".html"
addr3 = addr1 + "index" + addr2
print(addr3)

for i in range(2, 10):
    addr = addr1 + str(i) + addr2
    print(addr)

 

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

用函数得到校园新闻编号

s = 'http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1027/8443.html'
s2 = s.rstrip(".html").split("_")[1]
print(s2)

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

s = 'I am loving living every single day But sometimes I feel so I hope to find a little peace of mind And I just want to know ' \
    'And who can heal those tiny broken hearts And what are we to be Where is home on the Milky way of stars I dry my eyes again'
s2 = s.count('I')
print(s2)

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

s = 'I am loving living every single day But sometimes I feel so I hope to find a little peace of mind And I just want to know ' \
    'And who can heal those tiny broken hearts And what are we to be Where is home on the Milky way of stars I dry my eyes again'
s2 = s.split(" ")
print(s2)

 

2.组合数据类型练习

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

s = 'turtle'
for i in s:
    print(i)
ls = list('12345')
for s in ls:
    print(s)
tup = tuple('asadsa')
for i in tup:
    print(i)
d = dict(zip(['Bob','Mike'],['87','67']))
for i in d.keys():
    print(i)
for s in d.values():
    print(s)
for i in d.items():
    print(i)
s = set('13245')
for i in s:
    print(i)

 

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

列表和元组都是序列,有顺序的,可以按照序列号来查找对应的值,但是列表可以修改,而元组里的不能修改,除非元组的某个元素是列表。

字典和集合不是序列,没有顺序的,字典采用键值对存储,可通过键来查找值,而集合里面只存储键,不存储值,只是键的集合。字典和集合的值都是不能重复的。

 

posted @ 2018-03-21 17:12  050朱小彬  阅读(138)  评论(0编辑  收藏  举报