如何在某些索引处反转和连接字符串?

时间:2015-01-28 23:39:49

标签: python string python-3.x concatenation reverse

对于我的作业,我需要首先提出一个函数来反转输入的字符串(我已经使用下面的代码完成了)

def reverse(s):
    if len(s) <= 1:
        return s

    return reverse(s[1:]) + s[0]

接下来的部分是通过在某个索引值处断开它来构造一个给定的字符串,并将第二部分(后缀)的反向连接到第一部分的开头(前缀)

例如,如果输入字符串是&#39; laptop&#39;并且所选择的索引值是,例如,3,字符串被打破为&#39; lap&#39; +&#39; top&#39;。 &#39;顶部&#39;然后会被反转为“锅”。并将与前缀(在顺序中)连接为“锅”和“锅”。 +&#39;圈&#39;

这项任务有些令人困惑,因为我是一名新手,除了在Python工作几天之外几乎没有经验,我对于该怎么做有点困惑。我非常确定我必须使用切片和连接运算符,但我不确定如何构建适合上述条件的函数。有什么指针吗?

3 个答案:

答案 0 :(得分:1)

类似的东西:

def concatreverse(s, i):
    return s[:i] + reverse(s[i:])

答案 1 :(得分:1)

结合其他两个答案,并实现您的反向功能:

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

作为初学者,它有助于逐行逐步,或使用解释器进行测试以确切了解发生了什么:)

答案 2 :(得分:0)

你可以这样做:

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
相关问题