*禁白嫖*python----字符串相关操作方法
字符串的相关操作方法
以下以 字符串进行操作
str='hello my python world itcast pythonitcast'
![](https://img.haomeiwen.com/i22651072/40382a52ed0f0b56.png)
![](https://img.haomeiwen.com/i22651072/20fa2203ee3017f0.png)
#如果str的index方法中不包含此数据则会报错
print(str.index('itcast',0,10))
![](https://img.haomeiwen.com/i22651072/24a9e79ba5cd9b88.png)
#count是算出字符串中所包含的字符串个数
print(str.count('itcast'))
![](https://img.haomeiwen.com/i22651072/df71b89e5ab5d3a7.png)
#replace是将字符串进行替换
print(str.replace('python','PYTHON'))
![](https://img.haomeiwen.com/i22651072/895ab54b7cc37933.png)
#split方法是将字符串转化为列表print(str.split(' '))
#capitalize是将字符串的第一个字符转化为大写 title是将字符串的每一个单词首字母大写
print(str.capitalize(),str.title())
#加ing字符串转化为列表并且进行循环出来的字符串的startswith方法进行判断 是否以p开头
for iin str.split(' '):
#判断一下字符串是否以什么开头
if i.startswith('p'):
print('str is startswith p')
#判断一下字符串是否以什么结尾
elif i.endswith('cast'):
print('str is not startswith p but str is endswith cast')
else:
print('str is not startswith p and str is not endswith cast')
![](https://img.haomeiwen.com/i22651072/4bc0b08f2a85ed6d.png)
以下以字符串进行操作
mystr='Hello MY Python World '
#将字符串进行转化为小写和大写
print(mystr.lower(),mystr.upper())
![](https://img.haomeiwen.com/i22651072/f1ba5978bc2e4d37.png)
#返回一个源字符串左对齐/右对齐,并且使用空格填充至长度width的新字符串
print(mystr.ljust(30),'\n',mystr.rjust(20))
![](https://img.haomeiwen.com/i22651072/9922567b50aba579.png)
print(mystr.center(50),mystr.lstrip(),mystr.rstrip())
![](https://img.haomeiwen.com/i22651072/a59536c2404a6ce4.png)
#partition 将mystr以内容进行分割为前后
print(mystr.partition('Python'),'\n',mystr.rpartition('Python'))
![](https://img.haomeiwen.com/i22651072/0cea71f48dd17c34.png)
#splitlines 按照行数进行分割 返回一个包含各行行为元素的列表
print(mystr.splitlines())
![](https://img.haomeiwen.com/i22651072/9ab2dcf3f3a1a402.png)
#isalpha 如果所有字符都是字母则返回true
print(mystr.isalpha())
#isdigit 如果字符串中只包含数字则返回true 否则返回false
print(mystr.isdigit())
#isalnum判断一下字符串中是否都是数字或者字母返回true 否则返回false
print(mystr.isalnum())
#isspace 判断一下字符串中是否包含空格 ,包含的话返回true,否则返回false
print(mystr.isspace())
![](https://img.haomeiwen.com/i22651072/54739d057626700d.png)
#join在每个字符后面加入str 进行构建新的字符串
print('*'.join(mystr))
![](https://img.haomeiwen.com/i22651072/57620b71a4bf4d8b.png)