[英]How to reverse and concatenate strings at certain indexes?
对于我的作业,我首先需要提供一个函数,该函数可以反转输入的字符串(我已经使用下面的代码完成了此操作)
def reverse(s):
if len(s) <= 1:
return s
return reverse(s[1:]) + s[0]
下一部分是从给定的字符串中以一个特定的索引值将其断开,然后将第二部分的后缀(后缀)连接到第一部分的开头(前缀)来构造一个新字符串。
例如,如果输入字符串为“ laptop”,并且所选索引值为3,则该字符串将被打断为“ lap” +“ top”。 然后将“ top”反转为“ pot”,并将其与前缀(按顺序)连接为“ pot” +“ lap”
这项任务有些令人困惑,并且由于我是新手,除了在Python中工作几天外,几乎没有经验,所以我对做什么感到困惑。 我很确定我必须使用slice和串联运算符,但是我不确定应该如何构造适合上述条件的函数。 有指针吗?
就像是:
def concatreverse(s, i):
return s[:i] + reverse(s[i:])
结合其他两个答案,并实现反向功能:
def concatreverse(s, i):
"""This function takes in a string, s, which
is split at an index, i, reverses the second of the split,
and concatenates it back on to the first part"""
#Takes your inputs and processes
part1,part2 = s[0:i], s[i:]
#Reverse part2 with the function you already created
#this assumes it is accessible (in the same file, for instance)
rev_part2 = reverse(part2)
#concatenate the result
result = part1 +rev_part2
#Give it back to the caller
return result
作为初学者,它有助于一步一步地进行操作,或者使用解释器进行测试以查看发生了什么事:)
您可以执行以下操作:
s = 'laptop'
i = 3;
# split the string into two parts
part1,part2 = s[0:i], s[i:]
# make new string starting with reversed second part.
s2 = part2[::-1] + part1
print(s2)
# prints: potlap
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.