当前位置:脚本大全 > > 正文

python常用的字符串操作方法(Python字符串的常见操作实例小结)

时间:2021-10-22 07:15:11类别:脚本大全

python常用的字符串操作方法

Python字符串的常见操作实例小结

本文实例讲述了python字符串的常见操作。分享给大家供大家参考,具体如下:

如果我们想要查看以下功能:help(mystr .find)

1.find

例:

  • ?
  • 1
  • 2
  • mystr="hello world itcast"
  • print(mystr.find("world"))
  • 结果为

    6

    find括号中填写要查找的内容,如果找不到返回-1,找到返回从左往右找到的第一个位置

    2.index

    功能和find一样,只是找不到时,这个返回错误

    3.rfind

    从右往左找的第一个位置

    4.rindex

    从右往左找

    5.count

    统计字符串中出现的次数,没有出现一次返回0

    例:

  • ?
  • 1
  • mystr.count("itcast")
  • 结果为

    1

    6.replace

    替换,参数1:源  参数2:目标  但是原来的并没有改变,只是显示一次改变的结果,因为这是不可变类型,除非用一个变量重新接收

    例:

  • ?
  • 1
  • mystr.replace("world","world")
  • 用大写的替换小写的值

    7.split

    切割

    例:mystr.split(" ") 把有空格的都切割掉,按照空格切,按什么来切,什么就会没有,保存格式为列表的格式

    8.capitalize

    把第一个字母变成大写

  • ?
  • 1
  • 2
  • mystr ='hello world itcast'
  • print(mystr.capitalize())
  • 结果为:

    hello world itcast

    9.title

    字符串的每个首字母都大写

  • ?
  • 1
  • 2
  • mystr ='hello world itcast'
  • print(mystr.title())
  • 结果为:

    hello world itcast

    10.startswitch

    检查字符串是否以某个字符串开头,是返回true,否返回false  mystr.startswitch(obj)

    11.endwith

    检查字符串是否以某个字符串结尾

    12.lower

    转换mystr中所有大写字符为小写

    13.upper

    转换mystr中所有小写字符为大写

    14.ljust  rjust

    返回一个原字符串左(右)对齐,并使用空格填充至长度width的新字符串

    mystr.ljust(10)长度不够的用空格填充

    15.center

    返回一个原字符串居中,并使用空格填充长度width的新字符串

    16.lstrip rstrip strip

    删除mystr字符串前端的空白字符

    删除mystr字符串末端的空白字符

    删除mystr字符串两端的空白字符

    如果要删除多个不同字符串前后的空白字符和有\t出现的情况mystr.split()就什么都不加

    17.partition

    把mystr以str分割成三部分,str前,str和str后

  • ?
  • 1
  • 2
  • mystr='hello world itcast and it'
  • print(mystr.partition("itcast"))
  • 结果为:

    ('hello world','itcast','and it')

    18.rpartition lpartition

    从右边和从左边开始

    19.splitlines

    按照行分隔,返回一个包含各行作为元素的列表,按换行来切割

  • ?
  • 1
  • 2
  • mystr="hello\nworld"
  • print(mystr.splitlines())
  • 结果为:

    ['hello','world']

    20.isalpha

    如果mystr所有的字符都是字母,返回true

  • ?
  • 1
  • mystr.isalpha()
  • 21.isdigit

    判断是不是等于纯数字的字符串

    22.isalnum

    是不是字母和数字组合在字符串中

    23.isspace

    判断是不是纯空格

    24.join

    把字符串连接在一起

    例:

  • ?
  • 1
  • 2
  • 3
  • names=["aaa","bb","cc"]
  • a="_"
  • a.join(names)
  • 结果为:

    aaa_bb_cc

    希望本文所述对大家python程序设计有所帮助。

    原文链接:https://blog.csdn.net/chenjuan0530/article/details/78412938

    标签:
    上一篇下一篇

    猜您喜欢

    热门推荐