str常用函数

223 阅读2分钟

判断

isspace()

如果字符串中只包含(多个或者一个)空格,则返回 True,否则返回 False.

startswith(substr, beg=0,end=len(string))

检查字符串是否是以指定子字符串 substr 开头,是则返回 True,否则返回 False。如果 beg 和 end 指定值,则在指定范围内检查。

endswith(suffix, beg=0, end=len(string))

检查字符串是否以 obj 结束,如果 beg 或者 end 指定则检查指定的范围内是否以 obj 结束, 如果是,返回 True,否则返回 False.

查找

find(str, beg=0 end=len(string))

检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内, 如 果 包含返回开始的索引值,否则返回-1

rfind(str, beg=0,end=len(string))

类似于 find()函数,不过是从右边开始查找.

count(str, beg= 0,end=len(string))

返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的 次数

修改

replace(old, new [, max])

把 将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次。

lstrip()

截 掉 字符串左边的空格或指定字符。

rstrip()

删 除 字符串字符串末尾的空格.

strip([chars])

在字符串上执行 lstrip()和 rstrip()

lower()

转 换 字符串中所有大写字符为小写.

upper()

转 换 字符串中的小写字母为大写

swapcase()

将 字 符串中大写转换为小写,小写转换为大写

对齐

center(width, fillchar)

返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。

zfill (width)

返回长度为 width 的字符串,原字符串右对齐,前面填充 0

ljust(width[, fillchar])

返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为 空格