检查输入的字符是否为合法变量名(迭代)

目标:

  1.列表迭代示例(字符串,元组,字典等也是可迭代对象)
  2.如何判断是否为可迭代对象
  3.输入任意字符名称,检查是否为合法变量名

 


1.列表迭代示例

>>> alist = [10, 'hello', 20, 30]
>>> for i in alist:
...   print i
...
10
hello
20
30
>>> for i in range(len(alist)):
...   print i,alist[i]
...
0 10
1 hello
2 20
3 30
>>> for item,value in enumerate(alist):
...   print item,value
...
0 10
1 hello
2 20
3 30
>>> for i in enumerate(alist):
...   print i[0],i[1]
...
0 10
1 hello
2 20

 

2.判断是否为可迭代对象

>>> from collections import Iterable
>>> isinstance(1, Iterable)
False
>>> isinstance('abc', Iterable)
True
>>> isinstance([1,2,3], Iterable)
True
>>> isinstance({'name': 'xkops', 'age': 25}, Iterable)
True
>>> isinstance((1,2,3), Iterable)
True

 

3.输入任意字符名称,检查是否为合法变量名
•规则
  1.首字符是大小写字母或者下划线
  2.剩余字符是大小写字母、数字及下划线

 

代码如下:

[root@localhost python]# cat check_id.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import string

#定义合格变量名的规则
first_ch = string.letters + '_'
surplus_chs = string.digits + first_ch

def check_id(varname):
    '''检查首字符,不合格返回'''
    if varname[0] not in first_ch:
        return "%s第一个字符无效" % varname

    for ind, value in enumerate(varname[1:]):
        '''通过list迭代判断剩余字符是否合格,不合格返回并打印不合格字符的位置'''
        if value not in surplus_chs:
            return "%s的第%d个字符无效" % (varname,(ind + 2))

    return "%s是有效的变量" % varname

if __name__ == "__main__":
    varname = raw_input("请输入检查的变量名: ")
    print check_id(varname)

 

4.运行脚本测试效果

[root@localhost python]# python check_id.py
请输入检查的变量名: 1h
1h第一个字符无效
[root@localhost python]# python check_id.py
请输入检查的变量名: h@
h@的第2个字符无效
[root@localhost python]# python check_id.py
请输入检查的变量名: h1@st
h1@st的第3个字符无效
[root@localhost python]# python check_id.py
请输入检查的变量名: h1
h1是有效的变量

 

posted @ 2016-12-30 17:02  xkops  阅读(990)  评论(0编辑  收藏  举报