使用递归在字符串中添加字符和空格

2024-05-19 03:01:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个递归函数,其中输入是字符串,而在输出中,我们得到的是带空格的双字符。这是什么逻辑

def recursive(string):
     ...
     ...  

Input : "Hello"

Output : "HH ee ll ll oo"


Tags: 字符串helloinputoutputstringdefhh逻辑
3条回答
def recursive(string):
  if not string:
    return ''
  else:
    c = string[0]
    rest = string[1:]
    return c + c + ' ' + recursive(rest)

另一种方法是使用^{}方法:

>>> t = 'Hello'
           
>>> ' '.join('{0}{0}'.format(t[i]) for i in range(len(t)))
           
'HH ee ll ll oo'

为了好玩,您还可以使用一行正则表达式来处理此问题:

inp = "Hello"
output = re.sub(r'(.)', r'\1\1 ', inp)
print(output)  # HH ee ll ll oo

相关问题 更多 >

    热门问题