python之字符串查找与替换

任务描述

在大家日常工作使用Word编写文档的过程中,经常会遇到的一个问题是:发现前面写的文档中某个词用错了,需要换为另外一个词来表达。Word提供了全文查找与替换的功能,可以帮助用户很方便的处理这一问题。那么,这一功能最基础和核心的字符替换,如果我们要自己基于Python来实现,该怎么做呢?

本关的任务是,给定一个字符串,要利用Python提供的字符串处理方法,从该字符串中查找特定的词汇,并将其替换为另外一个更合适的词。

例如,给定一个字符串Where there are a will, there are a way,我们发现这句话中存在语法错误,其中are应该为is,需要通过字符串替换将其转换为Where there is a will, there is a way.

相关知识

本关的小目标是让读者学习并掌握Python中常用的字符串方法,包括字符串查找、字符串切分、字符串替换等。

字符串查找

Python提供了内置的字符串查找方法find(),利用该方法可以在一个较长的字符串中查找子字符串。如果该字符串中有一个或者多个子字符串,则该方法返回第一个子串所在位置的最左端索引;若没有找到符合条件的子串,则返回-1

find()方法的基本使用语法如下:

  1. source_string.find(sub_string)

其中,

  • source_string:源字符串
  • sub_string:待查的目标子字符串
  • find:字符串查找方法的语法关键字

例如,在一个字符串中查找两个单词的位置:

  1. # coding=utf-8
  2.  
  3. # 创建一个字符串
  4. source_string = 'The past is gone and static'
  5.  
  6. # 查看"past"在source_string字符串中的位置
  7. print(source_string.find('past'))
  8.  
  9. # 查看"love"在source_string字符串中的位置
  10. print(source_string.find('love'))

输出结果:
4
-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.  
  3. # 创建一个字符串circle
  4. source_string = 'The world is big'
  5.  
  6. # 利用replace()方法用子串"small"代替子串"big"
  7. print(source_string.replace('big','small'))

输出结果:
The world is small

字符串分割

Python提供了split()方法实现字符串分割。该方法根据提供的分隔符将一个字符串分割为字符列表,如果不提供分隔符则程序会默认把空格(制表、换行等)作为分隔符。其基本使用语法如下:

  1. source_string.split(separator)

其中,

  • source_string:待处理的源字符串
  • separator:分隔符
  • split:字符串分割方法的关键词

例如,用+/还有空格作为分隔符分割字符串。

  1. # coding = utf-8
  2.  
  3. # 待处理字符串source_string
  4. source_string = '1+2+3+4+5'
  5.  
  6. # 利用split()方法,按照`+`和`/`对source_string字符串进行分割
  7. print(source_string.split('+'))
  8. print(source_string.split('/'))

输出结果:

['1', '2', '3', '4', '5']
['1+2+3+4+5']

编程要求

本关的编程任务是补全src/Step3/method2.py文件的代码内容,实现如下功能:

  • step1: 查找输入字符串source_string中是否存在day这个子字符串,并打印输出查找结果;

  • step2: 对输入字符串source_string执行字符替换操作,将其中所有的day替换为time,并打印输出替换后的字符串;

  • step3:对step2进行替换操作后的新字符串,按照空格进行分割,并将分割后的字符列表打印输出出来。

测试说明

本关的测试文件是src/Step3/method2.py,测试过程如下:

  1. 读者将src/Step3/method2.py中的代码补充完毕,然后点击评测,平台自动编译并运行method2.py,并以标准输入方式提供测评输入;
  2. 平台获取程序的输出,然后将其与预期输出对比,如果一致则测试通过;否则测试失败。

以下是平台对src/Step3/method2.py的样例测试集(本测试用例中的^表示空格):

测试输入:
day is up
预期输出:
0
time is up
['time', 'is', 'up']

测试输入:
^^what is the time now?^
预期输出:
-1
^^what is the time now?^
['', '', 'what', 'is', 'the', 'time', 'now?', '']

测试输入:
How many days have you taken?
预期输出:
9
How many times have you taken?
['How', 'many', 'times', 'have', 'you', 'taken?']

# coding = utf-8

source_string = input()

# 请在下面添加代码
###### Begin ######
print(source_string.find("day"))
print(source_string.replace("day","time"))
print(source_string.replace("day","time").split(" "))

####### End #######

发布了87 篇原创文章 · 获赞 32 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/Andone_hsx/article/details/84789277