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

目标:

  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是有效的变量

 

转载于:https://www.cnblogs.com/xkops/p/6237622.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值