Python中的str字符串
字符串
- 一个个字符组成的有序序列,是字符的集合
- 可使用单引号、双引号、三引号
- 是不可变对象
- Python3起,字符串默认就是Unicode类型
字符串定义
S1 = 'string'
s1= "hello world"
S1 = '''hello
world'''
字符串访问
- 索引访问
sql = "select * from user"
sql[4]
- 可迭代
字符串连接
-
- 将两个字符串连接在一起
- 返回一个新字符串
-
join连接
- "string".join(iterable) —>str
- 将可迭代对象连接起来
- 可迭代对象本身元素都是字符串
- 返回一个新字符串
lst = ['1', '2', '3'] print("\n".join(lst)) # 换行输出 - "string".join(iterable) —>str
字符串切割
-
分隔字符串方法分为2类
-
split
- 将字符串按照分隔符分隔成若干字符串,并返回列表
- Split(sep=None, maxsplit=-1)
- 从左向右
- sep指定分隔字符串,默认为空白字符串作为分隔符
- maxsplit指定分隔的次数,-1表示遍历整个字符串
In [7]: s1 = "I'm \ta super student" In [8]: s1.split() Out[8]: ["I'm", 'a', 'super', 'student'] In [9]: s1.split('\t', maxsplit=2) Out[9]: ["I'm ", 'a super student'] -
rsplit(sep=None, maxsplit=-1)
- 从右至左
-
splitlines([keepends])
- 按照换行符来切分字符串
- keepends指的是是否保留行分隔符
-
partition
- 将字符串按照分隔符分隔成2段,返回这两段和分隔符的元组
- Partition(sep)
- 从左至右,遇到分隔符就把字符串分隔为两部分,返回头、分隔符、尾的三元组,如果没有找到分隔符,就返回头、2个空元素的三元组
- sep分隔符字符串,必须指定
In [15]: s1 = "I'm a super student" In [16]: s1.partition('super') Out[16]: ("I'm a ", 'super', ' student')
-
字符串大小写转换
- upper()
- 转换为全大写
- lower()
- 转换为全小写
- swapcase()
- 交互大小写
字符串修改
- 字符串不可修改,但可以创建为新的字符串
- replace(old, new[,count])
- 字符串中找到匹配替换的新子串,返回新字符串
- count表示替换几次,不指定为全部替换
In [18]: s1 = "I'm a super student"
In [19]: s1.replace('super','good')
Out[19]: "I'm a good student"
- strip([chars])
- 从字符串两端去除指定的字符集chars中的所有字符
- 如果chars没有指定,去除两端的空白字符
字符串查找
-
find(sub[, start[, end]])
- 在指定的区间,从左至右,查找子串sub,找到返回索引,找不到返回-1
-
count(sub[, start[, end]]))
- 在指定的区间,从左至右,统计子串sub出现的次数
字符串判断
- endswith(suffix [, start[, end]])
- 在指定的区间(satrt,end),字符串是否是suffix结尾
- startswith(suffix [, start[, end]])
- 在指定的区间(satrt,end),字符串是否是suffix开头
字符串判断
- isalnum() 是否是字母和数字组成
- isalpha() 是否是字母
- Isdigit() 是否全部是数字
- isidentifier() 是否字母和下划线开头,其他都是字母、数字
- islower() 是否全部小写
字符串格式化
-
字符串格式化
- join拼接只能使用分隔符,且要求被拼接的是可迭代对象
- 加号+拼接字符串,非字符串需要先转换为字符串才能拼接
-
C语言的格式化printf函数
- 要求占位符:使用%和格式字符组成,如%s、%d
- values职能是一个对象
>>> item = "apple" >>> print('this is a %s') % item this is a apple -
format函数格式字符串语法
-
"{} {xxx}".format(*args, **kwargs)
-
args是位置参数,是一个元组
-
kwargs是关键字参数,是一个字典
-
{}是占位符
-
{}表示按照顺序匹配位置参数,{n}表示取位置参数索引为n的值
-
{{}}表示打印花括号
-
示例:
1、位置参数
>>> "{}:{}".format("192.168.1.1", 8888) '192.168.1.1:8888'2、对象属性访问
from collections imports namedtuplePoint = namedtuple('Point', 'x y')p = Point(4, 5)"{{{0.x},{0.y}}}".format(p)3、对齐
>>> '{0}*{1}={2:<2}'.format(3,2,2*3)'3*2=6 ' # 左对齐两位>>> '{:^30}'.format('centered')' centered '# 居中补位 -

浙公网安备 33010602011771号