关于python之替换字符串

字符串 text= “hello world, hello python, hello code”;

三道题;1替换text的第一个hello为what,2替换text的第二个hello为what,3替换text的最后一个hello为what;

问题一:replace函数

text='hello world, hello python, hello code'
text=text.replace('hello','what',1)  #只替换一次,即count=1
print(text)
# 打印输出 what world, hello python, hello code

问题二:利用正则表达式库re

import re

text = "hello world, hello python, hello everyone"

def replace_second_str(text, pattern, replacement):
    matches = list(re.finditer(pattern, text))
    if len(matches) >= 2:
        start, end = matches[1].span()
        return text[:start] + replacement + text[end:]
    return text

text = replace_second_str(text, r'hello', 'waht')
print(text)
# 打印输出 hello world, what python, hello code

问题三:rfind函数

text = "hello world, hello python, hello everyone"

last_index = text.rfind("hello")  # 从右向左查找最后一个hello的位置
if last_index != -1:
    result = text[:last_index] + "what" + text[last_index + len("hello"):]
   #字符串拼接
else:
    result = text

print(result)
# 输出: hello world, hello python, what everyone

关于python之替换字符串

© 版权声明

相关文章

暂无评论

none
暂无评论...