Python字符串方法
方法 | 作用 |
---|---|
str1 = 'python’ str1 = str(123) | 新建字符串 |
len(str1) | 字符串长度 |
str1.find(‘2’) | 返回str出现的索引位置,找不到返回-1 |
str1.index(‘2’) | 找到返回索引,找不到异常报错 |
str1.replace(‘py’, ‘cpy’) | 将字符串中的py替换成cpy |
str1.count(‘1’) | 统计字符串中x出现的次数 |
str1.endswith(‘0’) | 字符串以str结尾否 |
str1.starswith(‘0’) | 字符串以str开头否 |
str1.isdigit() | 字符串全为数字否 |
str1.isalpha() | 字符串全为字母否 |
str1 = ‘你,我,他’ str1.split(’,’) | 对字符串进行分割,返回列表 |
str1.strip() | 去除字符串收尾指定的字符(默认为空格) |
str1[0] | 取字符串 |
str1[1:2:1] str1[2:] str1[:-1] str1[::-1] | 字符串切片,[起始下标,结束下标,步进] |
\ | 转义特殊字符 |
方式1: str1 = ‘h’ + ‘i’ 方式2: str2 = list(‘smile’) ’’.join(str2) 方式3: str3 = ‘今天周{},天气{}。’.format(‘六’, ‘晴’) | 拼接字符串 |
字符串特点
比较项 | 特点 |
---|---|
修改字符串 | 字符串不允许被直接修改, 但可通过replace(x,y)方法来修改字符串内容, 实际为在内存中新建内存块重写字符串。 |