Python 字符串查找、替换、分割

字符串查找

Python 提供了内置的字符串查找方法 find() ,利用该方法可以在一个较长的字符串中查找子字符串。

如果该字符串中,有一个或者多个子字符串,则该方法返回第一个子串所在位置的最左端索引;若没有找到符合条件的子串,则返回 -1。

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

source_string.find(sub_string)

其中:

source_string:源字符串;

sub_string:待查的目标子字符串;

find:字符串查找方法的语法关键字。

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

# coding=utf-8
# 创建一个字符串
source_string = 'The past is gone and static'
# 查看"past"在source_string字符串中的位置
print(source_string.find('past'))
# 查看"love"在source_string字符串中的位置
print(source_string.find('love'))

输出结果:

4
-1

字符串替换

Python 提供了 replace() 方法,用以替换给定字符串中的子串,其基本使用语法如下:

source_string.replace(old_string, new_string)

其中:

source_string:待处理的源字符串;

old_string:被替换的旧字符串;

new_string:替换的新字符串;

replace:字符串替换方法的语法关键词。

例如,在如下字符串中,用 small 子串替换 big 子串。

# coding = utf-8
# 创建一个字符串circle
source_string = 'The world is big'
# 利用replace()方法用子串"small"代替子串"big"
print(source_string.replace('big','small'))

输出结果:

The world is small

字符串分割

Python 提供了 split() 方法实现字符串分割

其基本使用语法如下:

source_string.split(separator)

其中:

source_string:待处理的源字符串;

separator:分隔符;

split:字符串分割方法的关键词。

测试要求:

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

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

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

代码:

# coding = utf-8
source_string = input()

# 请在下面添加代码
# ********** Begin ********** #
#查找输入字符串 source_string 中,是否存在 day 这个子字符串
#并打印输出查找结果;
step1 = source_string.find("day")
print(step1)
#对输入字符串 source_string 执行字符替换操作,
#将其中所有的 day 替换为 time,并打印输出替换后的字符串;
step2 = source_string.replace("day","time")
print(step2)
#对 step2 进行替换操作后的新字符串,按照空格进行分割,
#并将分割后的字符列表打印输出出来。
step3 = step2.split(" ")
print(step3)
# ********** End ********** #

测试输入:
All day is no day when it is past.

预期输出:

4
All time is no time when it is past.
['All', 'time', 'is', 'no', 'time', 'when', 'it', 'is', 'past.']
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值