美文网首页
python5字符串的各种内置方法

python5字符串的各种内置方法

作者: 菠萝_c93e | 来源:发表于2020-04-02 21:37 被阅读0次

1.字符串读取和插入

>>> str='asdfgh'
>>> str[2:]#读取str索引2之后的文字
'dfgh'
>>> str[2]#读取str索引2的文字
'd'
>>> str+'456'#str后插入456,但没有保存为一个标签,所以str仍为以前的值
'asdfgh456'
>>> str
'asdfgh'
>>> str=str+'456'#指定str+456保存为str,因此str变为str+456的值
>>> str
'asdfgh456'

2.capitalize()把字符串第一个字符改为大写
casefold()把字符串全部变成小写字母

>>> str1='abc'
>>> str1.capitalize()
'Abc'

>>> str2='ABC'
>>> str2.casefold()
'abc'

3.center(width)将字符居中,并使用空格填充至长度with的新字符串

>>> str2.center(50)
'                       ABC                        '
  1. count(sub[,star[,end]])返回sub在字符串出现的次数,star和end表示范围可选。
    endwith(sub[,star[,end]])检查字符是否以sub结束,如果是返回True,如果不是返回False
    expandtabs([tabsize=8])把字符中的Tab符号('\t')转换为空格,如果不指定参数则,空格数默认为tabsize=8
    find(sub[,star[,end]])检查sub是否包涵在字符串中,如果有则返回索引值,否则返回-1,star和end表示范围可选
    index(sub[,star[,end]])与find()相同,不过若sub不在字符串中,则产生一个异常
>>> str3='chenchenzuimeila'
>>> str3.count('chen')#count()查看str3中chen出现的次数
2
>>> str3.endswith('chen')#endswith查看str3的结束值是否为chen
False

>>> str4='I\tlove\tchenchen'
>>> str4.expandtabs()#str4中的\t更改为空格
'I       love    chenchen'
>>> str4.find('love')#查找love是否在str4中,并返回索引值
2
>>> str4.find('123')
-1
>>> str4.index('123')
Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    str4.index('123')
ValueError: substring not found

5.查看字符串的文字类型


搜狗截图20年04月02日2120_1.png

6.其他函数


搜狗截图20年04月02日2131_2.png
搜狗截图20年04月02日2133_3.png

相关文章

网友评论

      本文标题:python5字符串的各种内置方法

      本文链接:https://www.haomeiwen.com/subject/ljpfphtx.html