今天在练习一个字符串操作时,需要把大小写字母全部都保存到一个列表中。联想到shell中都有使用POSIX字符类,如[:alnum:]表示字母与数字字符,[:alpha:]表示字母字符, [:digit:]表示数字字符,python作为高级、流行的编程语言,理论上应该有提供类似功能的模块。
仔细查了下,发现string模块刚好符合我需要的功能,该模块包括了以下常量字符集。
The constants defined in this module are:
string.ascii_letters
The concatenation of the ascii_lowercase and ascii_uppercase constants described below. This value is not locale-dependent.
string.ascii_lowercase
The lowercase letters 'abcdefghijklmnopqrstuvwxyz'. This value is not locale-dependent and will not change.
string.ascii_uppercase
The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. This value is not locale-dependent and will not change.
string.digits
The string '0123456789'.
string.hexdigits
The string '0123456789abcdefABCDEF'.
string.octdigits
The string '01234567'.
string.punctuation
String of ASCII characters which are considered punctuation characters in the C locale.
string.printable
String of ASCII characters which are considered printable. This is a combination of digits, ascii_letters, punctuation, and whitespace.
string.whitespace
A string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.
这些常量把常用的一些字符集都列举出来了,我们可以根据自己的需要进行选择。
另外,string模块还有一个capwords函数,即把传入的字符串变成首字母大写。
string.capwords("abc,abc,test", sep=",")
'Abc,Abc,Test'