2016-11-14 64 views
0

问题已被问到是类似的,但这里的所有帖子都是指替换单个字符。我试图用一个字符串替换整个单词。我已经取代了它,但我无法打印它之间的空格。替换字符串,不使用字符而不使用.replace和加入字符串

这里是取代它的功能replace

replace('dogs', 'I like dogs', 'kelvin') 

我的结果是这样的:

i l i k e k e l v i n 

我正在寻找的是

def replace(a, b, c): 
    new = b.split() 
    result = '' 
    for x in new: 
     if x == a: 
      x = c 
     result +=x 
    print(' '.join(result)) 

与调用它:

I like kelvin 
+0

如何敏感,你需要注册后才能间距,例如,输入中有2个空格? – AChampion

+0

老实说不知道。 –

+0

您是否需要替换子字符串? '热狗 - > hotkelvin'? – AChampion

回答

0

子串和空间保存方法:

def replace(a, b, c): 
    # Find all indices where 'a' exists 
    xs = [] 
    x = b.find(a) 
    while x != -1: 
     xs.append(x) 
     x = b.find(a, x+len(a)) 

    # Use slice assignment (starting from the last index) 
    result = list(b) 
    for i in reversed(xs): 
     result[i:i+len(a)] = c 

    return ''.join(result) 

>>> replace('dogs', 'I like dogs dogsdogs and hotdogs', 'kelvin') 
'I like kelvin kelvinkelvin and hotkelvin' 
+0

在你的例子中,“i”是什么?我得到一个错误,说它没有定义,对不起,很麻烦 –

+0

最后一个问题,这个列表理解是什么意思?结果[i:i + len( a)] = b @AChampion –

+0

这是一个切片任务......不是一个列表理解,'x = [1,2,3,4]; x [1:3] = [5,6,7]','' x'现在等于'[1,5,6,7,4]'。 – AChampion

0

只是要result列表,并且加入将工作:

result = [] 

你只是生成一个长字符串并加入它的字符。

1

这里的问题是result是一个字符串,当调用join时,它会将result中的每个字符加入到一个空间中。

而是使用list,append(它比使用字符串上的+=还快)并通过解压将其打印出来。

即:

def replace(a, b, c): 
    new = b.split(' ') 
    result = [] 
    for x in new: 
     if x == a: 
      x = c 
     result.append(x) 
    print(*result) 

print(*result)将供应result列表作为位置参数,以打印该打印出来具有默认白色空间分离的元件。

"I like dogs".replace("dogs", "kelvin")当然可以在这里使用,但我敢肯定,这一点失败了。

+0

打印(*结果)中的星号是做什么的? –

+0

通过将列表中的所有元素作为参数传递给'print'来避免对'''.join()'的调用,实际上等同于调用:print(result [0],result [1],result [2] ,...)' – AChampion

+0

不要以为我的例子适用于您要查找的单词的多个实例。对此有何建议? –

相关问题