如何编写一个递归函数,它接受一个字符串参数并返回一个字符串,其中相邻的相同字符用空格分隔?
我编写了一个非递归函数来执行我想要的操作:
def space_adj(istr):
new_str = ''
delimiter = ' '
for i, ch in enumerate(istr[:len(istr)-1]):
if ch == istr[i+1]:
new_str += ch + delimiter
else:
new_str += ch
new_str += istr[-1]
return new_str
我希望它这样做:
>>> space_adj('abcdeffghhh')
'abcdef fgh h h'
最佳答案
实际上没有必要进行递归,但可以这样做:
delimiter = " "
def space_adj(istr):
if len(istr) < 2: # The end-condition for the recursion
return istr
result = space_adj(istr[:-1]) # Get result for the shorter string with recursion
if istr[-1] == istr[-2]:
return result + delimiter + istr[-1]
else:
return result + istr[-1]
请注意 istr[:len(istr)-1]
的较短语法 istr[:-1]
。
仅提及一种不相关的替代方案:您可以通过一个正则表达式替换来完成此操作:
import re
def space_adj(istr):
return re.sub(r"(\w)(?=\1)", r"\1 ", istr)
关于python - 用空格分隔相邻相同字符的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53085171/