Python学习(二):字符串常用函数有哪些?
1.检验字符串长度:len(str);
a = "hello python" len(a) 12 a = "hello python" len(a[::2]) ##从头取到尾,隔一个取值的长度 6
2.切割字符串:obj.split(str);
a = "hello python" a.split();##不指定即表示安装空格切割 ["hello","python"] b="abcdefghijk" b.split('f');##指定字符串f进行切割 ["abcde","ghijk"]
3.去收尾空格或过滤指定字符串:obj.strip();
a = " hello python " a.strip(); "hello python" a = ".........hello python........" a.strip('.'); "hello python"
4.转换大写:obj.upper();
a = "hello python" a.upper(); "HELLO PYTHON"
5.转换小写:obj.lower();
a = "HELLO PYTHON" a.lower(); "hello python"
6.首字母大写:obj.title();
a = "hello python" a.title(); "Hello Python"
7.句子首字母大写:captilize(str);
a = "hello python" a.captilize(); "Hello python"
8.字符串替换:obj.replace(strA,strB);
a = "hello python" a.replace('o','k'); "hellk pythkn"
a = "hello python"
a.replace('hello','hi');
"hi python"
9.字符串计数:obj.count(str);
a = "hello python" a.count('h'); 2
10.判断是否以某个字符串开头:startswidth();
a = "hello python" a.startswidth('hello'); True
11.判断是否以某个字符串结尾:endswidth();
a = "hello python" a.endswidth('hello'); False
12.查找字符串出现的位置:obj.find();
a = "hello python" a.find('p'); 6
a = "hello python......"
a.rfind('p');##反向查找,注意,反向查找的时候,同样的字符串为一个
6
13.合并列表的字符串:obj.join(Arr);
a = ["hello","python","world"] '-'.join(a); "hello-python-world"