Python的字符串内建函数
Python 的字符串常用内建函数:
1、大小写转换:
str=”hello world”
str.capitalize() #首字母转大写
’Hello world’
str.swapcase() #小写转大写,大写转小写
’HELLOWORLD’
str.upper() #小写转大写
’ HELLOWORLD’
str.lower() #大写转小写
”hello world”
2、对齐方式:
ljust(width[, fillchar]) 左对齐
rjust(width,[, fillchar]) 右对齐
center(width, fillchar) 居中
fillchar 为填充的字符,默认为空格。
print(str.ljust(20))
print(str.center(40))
3、
count(str, beg=0,end=len(string)):返回str 在 string 里面出现的次数
print(str.count("o"))
title():所有单词都是以大写开始,其余字母均为小写(见istitle())
print(str.title())
4、
len(string):返回字符串长度
区别: str"hello world"
print(str.__len__()) #依赖于类 print(len(str)) #不依赖于类
5、求最大/小值
max(str) \ min(str):返回字符串 str 中最大\最小的字母。
>>> str"hello world"
>>> max(str)
’w’
>>>min(str)
6、查找
find(str, beg=0end=len(string)) :检测 str 是否包含在字符串中 str.find("el")
rfind(str,beg=0,end=len(string)) :类似于 find()函数,但是从右边开始查找.
index(str, beg=0,end=len(string)) 跟find()方法一样
rindex( str, beg=0,end=len(string)) 类似于 index(),但是从右边开始.
7.去除空格
lstrip() #截掉字符串左边的空格或指定字符。
rstrip() #删除字符串末尾的空格.
strip([chars]) #在字符串上执行 lstrip()和 rstrip()
8.替换
replace(old, new [, max]): 替换,如果 max 指定,则替换不超过 max 次。
#replace原字符串不会 被改变
print(str.replace("ll","LL"))
9.
b=a 传递引用 b=[a:] 拷贝推导,生成新的对象,地址改变 eg:a=[1,2,3,4,5] b=a print(id(b),id(a)) b=a[:] print(id(b),id(a))
运行结果:
82912360 82912360
82913400 82912360
10.
ljust(),rjust,center():字符串怎样对齐 l左对齐,r又对齐
print(mystr.ljust(20,"XX"))使用XX填充
strip(),lstrip(),lstrip()去除空格
join():将字符串连接在一起
partition():mystr.partion("xxx")以此字符串为节点拆分
spltlines()按照字符串进行拆分,如果字符串有"\n"
isalpha():判断字符串是否是字母
isdigit():判断字符串是否是数字
isalnum()判断字符串是否是数字和字母
decode():解码
encode():编码