MST
星途 面试题库

面试题:Python字符串处理之替换特定子串

假设有一个字符串s = 'hello world, hello python',请使用Python编写代码将其中所有的'hello'替换为'hi',并返回替换后的字符串。同时说明你使用的方法的时间复杂度。
49.2万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
s = 'hello world, hello python'
new_s = s.replace('hello', 'hi')
print(new_s)

使用的replace方法时间复杂度为$O(n)$,其中$n$为字符串的长度。因为该方法需要遍历整个字符串来查找并替换目标子串。