Python 功能辅助
我是python新手,在一个练习中,我将创建一个与.replace方法相同的函数 到目前为止,我有:Python 功能辅助,python,Python,我是python新手,在一个练习中,我将创建一个与.replace方法相同的函数 到目前为止,我有: def replace_str (string, substring, replace): my_str = "" for index in range(len(string)): if string[index:index+len(substring)] == substring : my_str += replace e
def replace_str (string, substring, replace):
my_str = ""
for index in range(len(string)):
if string[index:index+len(substring)] == substring :
my_str += replace
else:
my_str += string[index]
return my_str
当使用以下设备进行测试时:
print (replace_str("hello", "ell", "xx"))
它返回:
hxxllo
我希望有人能帮我指出正确的方向,这样它就可以用“xx”替换“ell”,然后跳转到“o”并打印:
hxxo
与.replace string方法一样。通常,使用手动维护索引变量的
while
是一个坏主意,但是当需要在循环中操作索引时,它可以是一个好选项:
def replace_str(string, substring, replace):
my_str = ""
index = 0
while index < len(string):
if string[index:index+len(substring)] == substring:
my_str += replace
# advance index past the end of replaced part
else:
my_str += string[index]
# advance index to the next character
return my_str
def replace_str(字符串、子字符串、替换):
我的_str=“”
索引=0
当索引
请注意,
x.replace(y,z)
在y
为空时执行不同的操作。如果要匹配该行为,可能需要在代码中使用特殊情况。您可以执行以下操作:
import sys
def replace_str(string, substring, replace):
new_string = ''
substr_idx = 0
for character in string:
if character == substring[substr_idx]:
substr_idx += 1
else:
new_string += character
if substr_idx == len(substring):
new_string += replace
substr_idx = 0
return new_string
if len(sys.argv) != 4:
print("Usage: %s [string] [substring] [replace]" % sys.argv[0])
sys.exit(1)
print(replace_str(sys.argv[1], sys.argv[2], sys.argv[3]))
请注意,在列表(list.append是O(1))上使用str.join()命令的速度比上述方法快,但您说过不能使用string方法
用法示例:
$ python str.py hello ell pa
hpao
$ python str.py helloella ell pa
hpaopaa
这些类型的练习是最糟糕的。如果你不能导入任何东西,那么正则表达式就不存在了。它将索引推进到被替换部分的末尾,我无法计算…@user3321382:被替换部分有多长?从哪里开始?它在哪里结束?添加足够的
索引
,将其从原来的位置移到替换零件的末端。