python判断变量字符是否合法

'''
输入一个字符串,检查其写法是否是合法的python变量名.
输入样例1:
_hi-python
输出结果:
合法
输入样例2:
python&
输出结果:
不合法


'''
illegalpha=['False','None','True','and','as','assert','break','class','continue',
			'def','del','elif','else','except','finally','for','from','global',
			'if','import','in','is','lambda','nonlocal','not','or','pass','raise',
			'return','try','while','With','yield',
               "abs","all","any","basestring","bin","bool","bytearray","callable","chr",
               "classmethod","cmp","compile","complex","delattr","dict","dir","divmod",
               "enumerate","eval","execfile","file","filter","float","format","frozenset",
               "getattr","globals","hasattr","hash","help","hex","id","input","int",
               "isinstance","issubclass","iter","len","list","locals","long","map","max",
               "memoryview","min","next","object","oct","open","ord","pow","print",
               "property","range","raw_input","reduce","reload","repr","reversed",
               "zip","round","	set","setattr","slice","sorted","staticmethod","str",
               "sum","super","tuple","type","unichr","unicode","vars","xrange","Zip",
               "__import__","apply","buffer","coerce","intern"]
illegalpha1="*&^%$#@!~()-+= ,.\"\\/"

while True:
	mychar=input('输入字符串 ')
	num=0
	if mychar[0].isdigit() or mychar in illegalpha:
		print('不合法')
	else :
		for x in list(mychar):
			if x in illegalpha1:
				num+=1
		if num!=0:
			print('不合法')
		else:
			print('合法')

[‘False’,‘None’,‘True’,‘and’,‘as’,‘assert’,‘break’,‘class’,‘continue’,‘def’,‘del’,‘elif’,‘else’,‘except’,‘finally’,‘for’,‘from’,‘global’,‘if’,‘import’,‘in’,‘is’,‘lambda’,‘nonlocal’,‘not’,‘or’,‘pass’,‘raise’,‘return’,‘try’,‘while’,‘With’,‘yield’]
1、变量名的长度不受限制,但其中的字符必须是字母、数字、或者下划线( ) ,而不能使用空格、连字符、标点符号、引号或其他字符。
2、 变量名的第一个字符不能是数字,必须是字母或下划线。
3、Python区分大小写。
4、不能将Python关键字用作变量名。
内置函数:
“abs”,“all”,“any”,“basestring”,“bin”,“bool”,“bytearray”,“callable”,“chr”,
“classmethod”,“cmp”,“compile”," complex",“delattr”,“dict”,“dir”,“divmod”,
“enumerate”,“eval”,“execfile”,“file”,“filter”,“float”,“format”,“frozenset”,
“getattr”,“globals”,“hasattr”,“hash”,“help”,“hex”,“id”,“input”,“int”,
“isinstance”,“issubclass”,“iter”,“len”,“list”,“locals”,“long”,“map”,“max”,
“memoryview”,“min”,“next”,“object”,“oct”,“open”,“ord”,“pow”,“print”,
“property”,“range”,“raw_input”,“reduce”,“reload”,“repr”,“reversed”,
“zip”,“round”," set",“setattr”,“slice”,“sorted”,“staticmethod”,“str”,
“sum”,“super”,“tuple”,“type”,“unichr”,“unicode”,“vars”,“xrange”,“Zip”,
import”,“apply”,“buffer”,“coerce”,“intern”]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值