python字符串方法详解
2019-03-30 21:56
253 查看
print('I love you \n' *10)
(1)切片,顾头不顾尾
s=[1,2,3,4,5,6,7] s[5:1] s[1:-1] s[-5:-2] s[1:6:2] s[2:7:3] s[2::2]
(2)排序
#sorted(s,key = None(#可以填str.lower或其他),reverse = False(#逆序)),返回列表
#序列拆封
#比较字符ASCII码值的大小
#空格<数字<大写字母<小写字母
"A">'a' 'A'>'a' sorted('abAC',key = str.lower) sorted('abAC')
函数的使用
函数及使用 | 描述 |
---|---|
chr(u) | u为Unicode编码,返回其对应字符 |
— | — |
ord(x) | x为字符,返回其对应的Unicode编码 |
字符串类型判断
函数及使用 | 描述 |
---|---|
str.isdigit() | 是否全为数字0-9 |
str.isdecimal() | 是否只含十进制数字字符 |
str.isnumeric() | 是否只包含数字字符 |
str.isalnum() | 是否全为字母或数字 |
str.isalpha() | 是否全为字母 |
str.islower() | 是否全为小写 |
str.isupper() | 是否全为大写 |
str.istitle() | 是否为标题,即各单词首字母大写,其他小写 |
str.isspace() | 判断字符串是否是空白(空格,制表符、换行符等)字符,没有任何字符不算空白 |
str.isidentifier() | 是否满足标识符定义规则,也可以说是命名规则:只能是字母或下划线开头、不包含除数字、字母、和下划线以外的任意字符 |
str.isprintable() | 是否可打印字符(制表符,换行符不可打印,但空格可以打印) |
输入 | 输出 | 描述 |
---|---|---|
print(‘a34’.islower()) | True | 只判断字符串所含字母是否小写 |
print(‘AB34’.isupper()) | True | |
print(‘Aa Bc’.istitle()) | True | 中间有空格表示两个单词,每个首字母都要大写 |
print(‘Aa_Bc’.istitle()) | 下划线也行 | |
print(‘Aa bc’.istitle()) | False | b作为首字母要大写 |
print(‘Aa_bc’.istitle()) | False | b作为首字母要大写 |
print(‘Aa BC’.istitle()) | False | c作为非首字母要小写 |
print(’ '.isspace()) | True | 空格算空白,不填任何东西则不算 |
print(’ \t’.isspace()) | True | |
print(’ \n’.isspace()) | True | |
print(‘Aa BC’.isspace()) | False | 引号里有字符,所以不是空格,即使字符中间有空格 |
print(’ \t’.isprintable()) | False | |
print(‘2abc’.isidentifier()) | False |
函数及使用 | 描述 |
---|---|
str.lower() | 全部转为小写 |
str.upwer() | 全部转为大写 |
str.capitalize() | 转为首字母大写,其他字母小写 |
str.title() | 转为首字母大写 |
str.swapcase() | 大小写互换 |
#[]代表可选参数
填充及使用 | 描述 |
---|---|
str.center(width,[,fillchar]) | 将字符串居中,左右两边使用fillchar进行填充,使得整个字符串的长度为width,若不指定fillchar,则用空格 |
str.ljust(width,[,fillchar]) | 左对齐,即在字符串右边使用fillchar进行填充,使得整个字符串的长度为width |
str.rjust(width,[,fillchar]) | 右对齐,即在字符串左边使用fillchar进行填充,使得整个字符串的长度为width |
str.zfill(width) | 前方补0,若width长度小于字符串长度,则无法填充 |
注意的是,chars若是多个字符序列,移除时,只要是这个序列中的字符,都会被移除
修剪及使用 | 描述 |
---|---|
str.strip([chars]) | 移除左右两边字符chars,默认空白 |
str.lstrip([chars]) | 移除左右两边字符chars,默认空白 |
str.rstrip([chars]) | 移除左右两边字符chars,默认空白 |
相关文章推荐
- Python 字符串方法详解
- Python3内置字符串方法详解
- python字符串连接的三种方法及其效率、适用场景详解
- Python 字符串方法分类详解
- Python 字符串方法详解
- Python 字符串方法详解
- 对python 匹配字符串开头和结尾的方法详解
- Python 字符串方法详解
- Python内置字符串操作处理方法详解
- Python 字符串方法详解
- Python 3.x 字符串的makestrans函数和translate方法使用详解
- python字符串连接的三种方法及其效率、适用场景详解
- Python 字符串方法详解
- Python字符串方法详解
- 详解Python3中字符串中的数字提取方法
- Python 字符串方法详解
- Python内置字符串操作处理方法详解
- Python 字符串方法详解
- 详解Python3中字符串中的数字提取方法
- Python实现字符串格式化输出的方法详解