Python字符串方法:字符串查找、替换、分割

打印 上一主题 下一主题

主题 869|帖子 869|积分 2607

字符串查找

Python 提供了内置的字符串查找方法find(),利用该方法可以在一个较长的字符串中查找子字符串。如果该字符串中,有一个大概多个子字符串,则该方法返回第一个子串所在位置的最左端索引,若没有找到符合条件的子串,则返回-1。find()方法的基本利用语法如下:
  1. source_string.find(sub_string)
复制代码
其中:

  • source_string:源字符串;
  • sub_string:待查的目标子字符串;
  • find:字符串查找方法的语法关键字。
例如,在一个字符串中,查找两个单词的位置:
  1. # coding=utf-8
  2. # 创建一个字符串
  3. source_string = 'The past is gone and static'
  4. # 查看"past"在source_string字符串中的位置
  5. print(source_string.find('past'))
  6. # 查看"love"在source_string字符串中的位置
  7. print(source_string.find('love'))
  8. #输出结果:
  9. 4
  10. -1
复制代码
字符串替换

Python 提供了replace()方法,用以替换给定字符串中的子串。其基本利用语法如下:
  1. source_string.replace(old_string, new_string)
复制代码
其中:

  • source_string:待处理的源字符串;
  • old_string:被替换的旧字符串;
  • new_string:替换的新字符串;
  • replace:字符串替换方法的语法关键词。
例如,在如下字符串中,用small子串替换big子串:
  1. # coding = utf-8
  2. # 创建一个字符串circle
  3. source_string = 'The world is big'
  4. # 利用replace()方法用子串"small"代替子串"big"
  5. print(source_string.replace('big','small'))
  6. #输出结果:
  7. The world is small
复制代码
字符串分割

Python 提供了split()方法实现字符串分割。该方法根据提供的分隔符,将一个字符串分割为字符列表,如果不提供分隔符,则步调会默认把空格(制表、换行等)作为分隔符。其基本利用语法如下:
  1. source_string.split(separator)
复制代码
其中:

  • source_string:待处理的源字符串;
  • separator:分隔符;
  • split:字符串分割方法的关键词
例如,用+、/还有空格作为分隔符,分割字符串:
  1. # coding = utf-8
  2. # 待处理字符串source_string
  3. source_string = '1+2+3+4+5'
  4. # 利用split()方法,按照`+`和`/`对source_string字符串进行分割
  5. print(source_string.split('+'))
  6. print(source_string.split('/'))
  7. #输出结果:
  8. ['1', '2', '3', '4', '5']
  9. ['1+2+3+4+5']
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

罪恶克星

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表