答案是可以!
判断一个字符串位于另一个字符串中,可以使用序列的通用方法,也可以使用序列的内建方法。
>>> a = "23"
>>> b = "1234"
>>> a in b
True
>>>
string类型有数个函数用于获取某个字符串中的索引,出现的次数等等,所以可以使用x = "ssss",x.index(),x.count().
>>> string = "scgggb"
>>> string.count("ggg")
1
>>> string.find("ggg")
2
>>> string.rfind("ggg")
2
>>> string.index("ggg")
2
>>> string.rindex("ggg")
2
>>>
>>> string.index("csr")
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
string.index("csr")
ValueError: substring not found
>>> string.find("fff")
-1
index和rindex一个从左边开始查找,一个从右边开始查找,index和find函数的相同之处在于,包含要寻找的字符串时,均返回索引,区别在于,找不到要寻找的字符串时,index函数返回一个异常,find函数返回-1.
6–2. 字符串标识符.修改例 6-1 的 idcheck.py 脚本,使之可以检测长度为一的标识符,并且可以识别 Python 关键字,对后一个要求,你可以使用 keyword 模块(特别是 keyword.kelist)来帮你.
#!/usr/bin/env python
import string
import keyword
import sys
import traceback
try:
#Get all keyword for python
#keyword.kwlist
#['and', 'as', 'assert', 'break', ...]
keyWords = keyword.kwlist
#Get all character for identifier
#string.letters ==> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
#string.digits ==> '0123456789'
charForId = string.letters + "_"
numForId = string.digits
idInput = raw_input("Input your words,please!")
if idInput in keyWords:
print "%s is keyword fot Python!" % idInput
else:
lenNum = len(idInput)
if(1 == lenNum):
if(idInput in charForId and idInput != "_"):
print "%s is legal identifier for Python!" % idInput
else:
#It's just "_"
print "%s isn't legal identifier for Python!" % idInput
else:
if(idInput[0:1] in charForId):
legalstring = charForId + numForId
for item in idInput[1:]:
if (item not in legalstring):
print "%s isn't legal identifier for Python!" % idInput
sys.exit()
print "%s is legal identifier for Python!2" % idInput
else:
print "%s isn't legal identifier for Python!3" % idInput
except SystemExit:
pass
except:
traceback.print_exc()
6–3. 排序
(a) 输入一串数字,从大到小排列之.
(b) 跟 a 一样,不过要用字典序从大到小排列之.
6–4. 算术. 更新上一章里面你的得分测试练习方案,把测试得分放到一个列表中去.你的代码应该可以计算出一个平均分,见练习 2-9 和练习 5-3.
6–5. 字符串
(a)更新你在练习 2-7 里面的方案,使之可以每次向前向后都显示一个字符串的一个字符.
(b)通过扫描来判断两个字符串是否匹配(不能使用比较操作符或者 cmp()内建函数)。附加题:
(c)判断一个字符串是否重现(后面跟前面的一致).附加题:在处理除了严格的回文之外,加入对例如控制符号和空格的支持。
判断一个字符串是否重现:for i in range(len(x)):
if (y == x[i:(i+4)]):
print "Yes"