Python中的常见字符串操作
Python标准库中的字符串模块提供了以下有用的常量,类和称为的辅助函数capwords()
常数
输出结果
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.octdigits
'01234567'
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.whitespace
' \t\n\r\x0b\x0c'Capwords()函数
此功能执行以下操作-
使用str.split()将给定的字符串参数拆分为单词。
使用str.capitalize()将每个词大写
并使用str.join()连接大写单词。
示例
>>> text='All animals are equal. Some are more equal' >>> string.capwords(text) 'All Animals Are Equal. Some Are More Equal'
格式化程序类
Python的内置str类具有format()使用可格式化字符串的方法。Formatter对象的行为类似。这可以通过子类化Formatter类来编写自定义的Formatter类。
>>> from string import Formatter
>>> f=Formatter()
>>> f.format('name:{name}, age:{age}, marks:{marks}', name='Rahul', age=30, marks=50)
'name:Rahul, age:30, marks:50'模板
此类用于创建字符串模板。它被证明对更简单的字符串替换很有用。
>>> from string import Template >>> text='My name is $name. I am $age years old' >>> t=Template(text) >>> t.substitute(name='Rahul', age=30) 'My name is Rahul. I am 30 years old'