Python string模块

Python string模块

使用string模块预定义的字符串所有字母和数字。在使用前需要先import。

>>> import string
>>> dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_sentinel_dict', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']

 

 string.ascii_uppercase:所有大写字母

string.ascii_lowercase:所有小写字母

string.ascii_letters:所有字母(大小写)

string.digits:十进制数字

string.octdigits:八进制数字

 string.hexdigits:十六进制数

>>> string.ascii_uppercase                  # 所有大写字母
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase                  # 所有小写字母
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_letters                    # 所有字母
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits                           # 十进制数字
'0123456789'
>>> string.octdigits                        # 八进制数字
'01234567'
>>> string.hexdigits                        # 十六进制数字
'0123456789abcdefABCDEF'

 

判断字符是否为字母或者数字:

>>> s = '1a2@f9s#'
>>> for i in s:
...     if i in string.ascii_letters:
...         print(i, '是字母')
...     elif i in string.digits:
...         print(i, '是数字')
...     else:
...         print(i, '是其他字符')
... 
1 是数字
a 是字母
2 是数字
@ 是其他字符
f 是字母
9 是数字
s 是字母
# 是其他字符

标识符合法性检查,首先要以字母或者下划线开始,后面要跟字母或者数字(只检查长度大于等于2的标识符)

#!usr/bin/evn python3


import string

alphas = string.ascii_letters + '_'
nums = string.digits

print('Welcome to the Identifier Checker V1.0')
print('Testees must be at least 2 chars long')

myInput = input('Identifier to test?')

if len(myInput) > 1:
    if myInput[0] not in alphas:		# 判断首字符是否符合是字母或者下划线
        print("invalid: first symbol must be alphabetic")
    else:
        alphnums = alphas + nums
        for otherChar in myInput[1:]:
            if otherChar not in alphnums: 
                print("invalid: remaining symbols must be alphanumeric")
                break
        else:				# 如果for循环中的break不执行,循环结束后,执行此else语句
            print("okay as an identifier")

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值