欢迎访问宙启技术站
智能推送

Python中实现基本的字符串查找和替换函数

发布时间:2023-07-05 22:25:43

Python中可以使用内置函数来实现基本的字符串查找和替换功能。以下是两个常用的函数示例:

字符串查找:使用find()函数可以在一个字符串中查找指定的子串。

def find_string(s, target):
    index = s.find(target)
    if index != -1:  # 如果找到了目标子串
        return f"目标子串在字符串中的位置:{index}"
    else:  # 如果没有找到目标子串
        return "目标子串不存在"

s = "Hello, world!"
target = "world"
result = find_string(s, target)
print(result)

输出结果为:“目标子串在字符串中的位置:7”。

字符串替换:使用replace()函数可以将一个字符串中的指定子串替换为另一个字符串。

def replace_string(s, old, new):
    new_string = s.replace(old, new)
    return f"替换后的字符串:{new_string}"

s = "Hello, world!"
old = "world"
new = "Python"
result = replace_string(s, old, new)
print(result)

输出结果为:“替换后的字符串:Hello, Python!”。

以上是两个基本的字符串查找和替换函数的示例。实际应用中,可以根据具体需求灵活运用这两个函数来完成更复杂的任务。