文章目录

  • str类简介
  • str的构造函数/方法
  • str的其他方法
  • str.capitalize()
  • str.casefold() 与str.lower()
  • str.center(width [, fillchar])
  • str.count(sub [, start [, end]])


str类简介

Python的字符串实际上是str类的实例。str类定义了许多方法辅助字符串操作。

>>> type("abc")
<class 'str'>

>>> dir(str) # list methods of str in alphabetic order
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', 
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', 
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', 
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', 
'__sizeof__', '__str__', '__subclasshook__', 
'capitalize', 'casefold', 'center', 'count', 'encode', 
'endswith', 'expandtabs', 'find', 'format', 'format_map', 
'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 
'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 
'isspace', 'istitle', 'isupper', 'join', 'ljust', 
'lower', 'lstrip', 'maketrans', 'partition', 'replace', 
'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 
'swapcase', 'title', 'translate', 'upper', 'zfill']

str的构造函数/方法

class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')

这是将其他类型的对象转换成字符串的方法。当将某个对象传递给str的构造函数时,会调用对象的__str__()方法,这个方法生成该对象的字符串表示。如果对象没有定义__str__()方法,则str会返回repr(object)的结果。例如,对于复数对象,则返回复数的字符串表示。

# construct a complex and return the string representation of the complex object
>>> str(complex(10,5)) 
'(10+5j)'
>>> repr(complex(10,5))
'(10+5j)'

TODO: add encoding description

str的其他方法

str.capitalize()

返回一个新的字符串,首字母大写,其余字符均小写。

>>> "HELLO WORLD".capitalize()
'Hello world'

str.casefold() 与str.lower()

str.lower()返回一个新字符串,将所有的区分大小写字母全部转换成小写字母,其余字母不变。

Python v3.3中新引入了str.casefold()方法,也返回一个新字符串,作用类似于lower()方法,但是行为更加激进。它会试图将所有的大小写区别都剔除掉。例如,对于德语,小写字母’ß’与’ss’是等价的,由于’ß’已经是小写字母了,所以lower()并不对其进行处理,但是casefold()会将其转换为’ss’。详细的casefolding的转换算法记述在Python文档的Unicode Standard章节中。

这两个函数返回的字符串通常可以用于不区分大小写的字符串比较操作当中。

注:对于26个英语字母而言,lower()与casefold()的行为没有区别

>>> "HELLO WORLD".lower()
'hello world'
>>> "HELLO WORLD".casefold()
'hello world'

>>> 'ß'.lower()
'ß'
>>> 'ß'.casefold()
'ss'

str.center(width [, fillchar])

返回一个新字符串,总长度是width,源字符串对象位于新字符串的中间位置,两头使用fillchar指定的字符填充(只能指定一个填充字符),未指定时fillchar默认是ASCII空格。如果指定的总长度小于源字符串长度,则返回整个源字符串,并不会进行截断操作。

>>> "HELLO WORLD".center(30, "*")
'*********HELLO WORLD**********'

>>> "HELLO WORLD".center(5, "*")
'HELLO WORLD'

# padding character can only be one character long.
>>> "HELLO WORLD".center(5, "*@")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long

str.count(sub [, start [, end]])

返回不重叠的子串sub的计数次数,查找范围由可选的start, end指定,含义用法与字符串切片操作相同,即start指定起始字符(含),end指定结束字符(不含)。未指定范围则查找整个字符串。

注意,这里“不重叠”是指已经匹配到的子串,全部或部分都不会被再次用于匹配(参看下例),而且查找操作是大小写敏感的。

>>> "AAAAA".count("AAA") # non-overlapping
1
>>> "AAAAA".count("AA") # non-overlapping
2
>>> "AAAAA".count("A") 
5

# case-sensitive count
>>> "HELLO WORLD".count("LL")
1
>>> "HELLO WORLD".count("ll")
0