第三节课 Python基本数据类型作业课

一.已有字符串 s = "i,am,lilei",请用两种办法取出之间的“am”字符。

s[2:4]
s[s.find("am"):s.find("am")+len("am")]


二.在python中,如何修改字符串?

a = "abc"
b = a.replace("b","a")
a = b

 

三.bool("2012" == 2012) 的结果是什么。
Flase

四.已知一个文件 test.txt,内容如下:

____________
2012来了。
2012不是世界末日。
2012欢乐多。
_____________

1.请输出其内容。
2.请计算该文本的原始长度。
3.请去除该文本的换行。
4.请替换其中的字符"2012"为"2013"。
5.请取出最中间的长度为5的子串。
6.请取出最后2个字符。
7.请从字符串的最初开始,截断该字符串,使其长度为11.
8.请将{4}中的字符串保存为test1.py文本.

a = open("test.txt","r")
content = a.read()
dcontent = content.decode('utf-8')
print len(dcontent)

rn_dcontent = dcontent.replace("\n","")
print rn_dcontent

d = rn_dcontent.replace("2012","2013")
print d

e = d[d.find("2013",5):d.find("2013",5)+5]
print e

print d[-2:len(d)]
print d[-2:]
print "".join([d[-2],d[-1]])

print d[0:11]


rinfo = content.replace("2012","2013")
f = open("test1.txt","w")
f.write(rinfo)
f.close()

 

五.请用代码的形式描述python的引用机制。


import sys
a = 1
print id(a)
print sys.getrefcount(1)

a = 2
print id(a)
print sys.getrefcount(2)

b = 1
print id(b)
print sys.getrefcount(1)

 

 

六.已知如下代码

________

a = "中文编程"
b = a
c = a
a = "python编程"
b = u'%s' %a
d = "中文编程"
e = a
c = b
b2 = a.replace("中","中")
________

1.请给出str对象"中文编程"的引用计数
2.请给出str对象"python编程"的引用计数


import sys
a = "中文编程"
b = a
print sys.getrefcount("中文编程")

c = a
print sys.getrefcount("中文编程")


a = "python编程"
print sys.getrefcount("中文编程")


b = u'%s' %a.decode("utf-8")
print sys.getrefcount("中文编程")


d = "中文编程"
print sys.getrefcount("中文编程")

e = a
print sys.getrefcount("中文编程")

c = b
print sys.getrefcount("中文编程")

b2 = a.replace("中","中")
print sys.getrefcount("中文编程")

 


七.已知如下变量
________
a = "字符串拼接1"
b = "字符串拼接2"
________

1.请用四种以上的方式将a与b拼接成字符串c。并指出每一种方法的优劣。
2.请将a与b拼接成字符串c,并用逗号分隔。
3.请计算出新拼接出来的字符串长度,并取出其中的第七个字符。


a = "字符串拼接1"
b = "字符串拼接2"

print a+b
print "%s%s" % (a,b)
print "{}{}".format(a,b)
print "".join([a,b])
print ",".join([a,b])

c = "".join([a,b])
print len(c.decode("utf-8"))

print c.decode('utf-8')[6].encode('utf-8')

 

八.请阅读string模块,并且,根据string模块的内置方法输出如下几题的答案。

1.包含0-9的数字。
2.所有小写字母。
3.所有标点符号。
4.所有大写字母和小写字母。
5.请使用你认为最好的办法将{1}-{4}点中的字符串拼接成一个字符串。

九.已知字符串
________

a = "i,am,a,boy,in,china"
________

1.假设boy和china是随时可能变换的,例boy可能改成girl或者gay,而china可能会改成别的国家,你会如何将上面的字符串,变为可配置的。
2.请使用2种办法取出其间的字符"boy"和"china"。
3.请找出第一个"i"出现的位置。
4.请找出"china"中的"i"字符在字符串a中的位置。
5.请计算该字符串一共有几个逗号。


a1 = "boy"
a2 = "china"
a = "i,am,a,{name},in,{nation}".format(name = a1, nation = a2)
b = "i,am,a,%(name)s,in,%(nation)s" %{'name':a1, 'nation':a2}
print a
print b

a = 'i,am,a,boy,in,china'

print a[a.find("boy"):a.find("boy")+len("boy")]
print a[a.find("china"):a.find("china")+len("china")]

print a.split(",")[3]
print a.split(",")[5]

print a.find("i")
print a.index("i")

print a.find("i",a.find("china"))
print a.rfind("i")
print a.count(",")


十.请将模块string的帮助文档保存为一个文件。

 

posted on 2016-05-19 22:59  慧命  阅读(555)  评论(0编辑  收藏  举报

导航