0


Python string模块

Python string模块

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

  1. >>> import string
  2. >>> dir(string)
  3. ['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:十六进制数

  1. >>> string.ascii_uppercase # 所有大写字母
  2. 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  3. >>> string.ascii_lowercase # 所有小写字母
  4. 'abcdefghijklmnopqrstuvwxyz'
  5. >>> string.ascii_letters # 所有字母
  6. 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  7. >>> string.digits # 十进制数字
  8. '0123456789'
  9. >>> string.octdigits # 八进制数字
  10. '01234567'
  11. >>> string.hexdigits # 十六进制数字
  12. '0123456789abcdefABCDEF'

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

  1. >>> s = '1a2@f9s#'
  2. >>> for i in s:
  3. ... if i in string.ascii_letters:
  4. ... print(i, '是字母')
  5. ... elif i in string.digits:
  6. ... print(i, '是数字')
  7. ... else:
  8. ... print(i, '是其他字符')
  9. ...
  10. 1 是数字
  11. a 是字母
  12. 2 是数字
  13. @ 是其他字符
  14. f 是字母
  15. 9 是数字
  16. s 是字母
  17. # 是其他字符

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

  1. #!usr/bin/evn python3
  2. import string
  3. alphas = string.ascii_letters + '_'
  4. nums = string.digits
  5. print('Welcome to the Identifier Checker V1.0')
  6. print('Testees must be at least 2 chars long')
  7. myInput = input('Identifier to test?')
  8. if len(myInput) > 1:
  9. if myInput[0] not in alphas: # 判断首字符是否符合是字母或者下划线
  10. print("invalid: first symbol must be alphabetic")
  11. else:
  12. alphnums = alphas + nums
  13. for otherChar in myInput[1:]:
  14. if otherChar not in alphnums:
  15. print("invalid: remaining symbols must be alphanumeric")
  16. break
  17. else: # 如果for循环中的break不执行,循环结束后,执行此else语句
  18. print("okay as an identifier")
标签: python 字符串

本文转载自: https://blog.csdn.net/zixuan020929/article/details/115639907
版权归原作者 zixuan020929 所有, 如有侵权,请联系我们删除。

“Python string模块”的评论:

还没有评论