Python build-in数据类型之字符串str (一)
在Python里文本数据是用str字符串类型来实现,用单引号'或者双引号" 括起来的任意文本。
比如'abc', "123abc", 注: '''triple quotes''' 以及 """three double-quotes""" 也是有效的
>>> '''triple quotes'''
'triple quotes'
>>> """three double-quotes"""
'three double-quotes'
另外下面这种方式也是合法的,引号之间的空格会被忽略掉
>>> x = "mash " "potato " "tastes " "good"
>>> x
'mash potato tastes good'
字符串是不可更改类型,也就是说一旦初始化就不能修改
example:
>>> s = "ABCD" >>> s[0] 'A' >>> s[0] = 'F' #尝试将首字符改成 F TypeError: 'str' object does not support item assignment
string方法介绍
str.capitalize() --返回该字符串的拷贝,并将首字母大写,其余的小写 example:
>>> 'hEllO WORLD'.capitalize() 'Hello world'
str.lower() --返回该字符串的拷贝,所有字母小写
str.upper() --返回该字符串的拷贝,所有字母大写
str.casefold() --与lower()相似,也是返回小写,区别是lower()只对英文字母'A-Z'有效,但是其他语言中的小写情况就无效了,这时我们就需要用casefold()
example:德语里 'ß' 的小写是 'ss'
>>> s = 'ß' >>> s.lower() 'ß' >>> s.casefold() 'ss'
str.
center
(width[, fillchar])
参数:width--指定返回字符串的宽度, fillchar用来填充的字符,默认是空格
返回值:返回一个指定宽度的字符串,原字符串置于中间,收尾用fillchar填充,如果指定的宽度小于或等于原字符串的长度,则返回原字符串
example:
>>> s= 'abc' >>> s.center(10) ' abc ' >>> s.center(3) 'abc' >>> s.center(7,'s') 'ssabcss' >>> s.center(9, '#') '###abc###'
str.count(sub, start = 0, end = len(str))--返回某个字符在字符串中指定的范围内出现的次数,默认起始位置是0,结束位置是len(str)。
str.encode(encoding='utf-8', error='strict')--以指定的编码方式编码字符串,默认是utf-8, error指定不同的错误处理方案。
str.decode(encoding='utf-8', error='strict')--以指定的编码方式解码字符串
example:
>>> s = '你好' >>> s.encode() b'\xe4\xbd\xa0\xe5\xa5\xbd' >>> s.encode('gb2312', 'strict') b'\xc4\xe3\xba\xc3' >>> x = b'\xc4\xe3\xba\xc3' >>> x.decode('gb2312', 'strict') '你好'
str.endswith(suffix[, start[, end]])--判断字符串是否以指定字符串sufix结尾,返回True,False。start、end指定检索范围,默认start = 0, end = len(str)。sufix可是一个字符串,也可以是一个字符串元组。
example:
>>> s = '人生苦短,我用Python' >>> s.endswith('on') True >>> s.endswith('on', 2, 6) False >>> s.endswith(('n', '生', '我'),2,5) False >>> s.endswith(('n', '生', '我'),2,6) True >>> s.endswith('n',0,13) True >>> s.endswith('n',0,12) False