python字符串基本操作,比如字符串的替换、删除、截取、复制、连接、分割等。都是一些关于字符串的一些方法。下面来列举一些,相信对学习python还是有些帮助的。
1.去除空格--strp();
>>> a=" winner " >>> a ' winner ' >>> b=a.strip() >>> print(b) winner
还可以使用lstrip()或者rstrip()来删除左边或者右边的空格
>>> a=' winner ' >>> a ' winner ' >>> a.lstrip() 'winner ' >>> a.rstrip() ' winner' >>>
2.字符串的复制
可以使用*运算符
>>> a="python" >>> b=a*5 >>> print(b) pythonpythonpythonpythonpython
也可以使用循环语句
>>> str1='and one ' >>> for i in range(5): print(str1) and one and one and one and one and one
3.连接字符串
用+连接
>>> a='this ' >>> b='is ' >>> c='why ' >>> d='we ' >>> e='play' >>> print(a+b+c+d+e) this is why we play
4.查找字符串
str.index()方法:检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内。
语法:str.index(str, beg=0, end=len(string)) str---指定检索的字符串; beg--开始索引,默认值为0; end--结束索引,默认为字符串的长度。
返回值:如果包含子字符串返回开始的索引值,否则抛出异常。
>>> a='hello world' >>> a.index('l') 2 >>> a.index('b') Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> a.index('b') ValueError: substring not found
str.find()方法:
str.find(str, beg=0, end=len(string))
返回值:如果包含子字符串返回开始的索引值,否则返回-1。
>>> a='hello world' >>> a.find('w') 6 >>> a.find('c') -1
5.是否包含指定字符串
in |not in
>>> a='hello world' >>> 'hello' in a True >>> 'hi' in a False >>> '123' not in a True
6.字符串长度。
str.len
>>> a='world i am watching you' >>> print(len(a)) 23
7.字符串中字母大小写转换
str.lower()转换为小写。
>>> a='PYTHON' >>> print(a.lower()) python
str.upper()转换为大写
>>> b='kingdom' >>> print(b.upper()) KINGDOM
str.swapcase()大小写互换
>>> c='Only One' >>> print(c.swapcase()) oNLY oNE
str.capitalize()首字母大写
>>> d='hello world' >>> print(d.capitalize()) Hello world
8.将字符串放入中心位置,以及两边字符的修饰。
str.center(width[, fillchar]) width--字符串的总宽度;fillchar--填充字符
>>> a="欢迎!" >>> print(a.center(40,'*')) ******************欢迎!*******************
9.字符串统计
str.count()
>>> a='sauwiqjaiwaa' >>> print(a.count('a')) 4
10.字符串切片
>>> a="你的魔法也救不了你" >>> print(a[:-1]) 你的魔法也救不了 >>> >>> print(a[0:3]) 你的魔
相关练习;
1.定义两个字符串分别为 xyz 、abc
2.对两个字符串进行连接
3.取出xyz字符串的第二个和第三个元素
4.对abc输出10次
5.判断a字符(串)在 xyz 和 abc 两个字符串中是否存在,并进行输出
>>> m='xyz' >>> n='abc' >>> print(m+n) xyzabc >>> print(m[1:]) yz >>> for i in range(10): print(n) abc abc abc abc abc abc abc abc abc abc >>> 'a' in m False >>> 'a' in n True