字符串操作符
比较操作符:字符串大小按ASCLL码值大小进行比较
切片操作符:[]、[:]、[::]
成员关系操作符:in、not in
脚本:判断用户输入的id是否符合要求
#!/usr/bin/env python
import string
#定义字符的范围
first_id = string.letters + "_" //确定首字符的范围
all_id = string.digits + first_id //确定其他字符的范围
#请求用户输入id
myid = raw_input("input your id: ") //请求用户输入id
#判断id是否合法
if len(myid) < 2:
print " you must input id longer then 2. "
else:
if myid[0] not in first_id:
print "first char %s is invalid" % (myid[0])
else:
for ch in myid[1:]:
if ch not in all_id:
print "other char invalid"
break
else:
print "%s is valid" % (myid)
以下将判断写成了函数,可以调用
#!/usr/bin/env python
import string
first_chr = string.letters + "_"
all_chr = first_chr + string.digits
myid = raw_input("input your id: ")
def id_check(myid):
if len(myid) < 2:
print "you must input char longer than 2. "
else:
if myid[0] not in first_chr:
print "your first char is invalid"
else:
for i in range(len(myid[1:])):
ind = i + 1
if myid[ind] not in all_chr:
print "char is invalid in position %s" % ind
else:
print "your id is valid"
if __name__ == "__main__":
id_check("123")
id_check("abc")