2024-05-19 03:01:42 发布
网友
我有一个递归函数,其中输入是字符串,而在输出中,我们得到的是带空格的双字符。这是什么逻辑
def recursive(string): ... ...
Input : "Hello"Output : "HH ee ll ll oo"
Input : "Hello"
Output : "HH ee ll ll oo"
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
另一种方法是使用^{} 方法:
为了好玩,您还可以使用一行正则表达式来处理此问题:
相关问题 更多 >
编程相关推荐