简体   繁体   English

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

[英]How to reverse and concatenate strings at certain indexes?

For my assignment, I'm required to first come up with a function that reverses a string that is inputted (which I've already done using the code below) 对于我的作业,我首先需要提供一个函数,该函数可以反转输入的字符串(我已经使用下面的代码完成了此操作)

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

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

The next part is to construct a new string from a given one by breaking it at a certain index value, and concatenating the reverse of the second part (the suffix) to the beginning of the first part (the prefix) 下一部分是从给定的字符串中以一个特定的索引值将其断开,然后将第二部分的后缀(后缀)连接到第一部分的开头(前缀)来构造一个新字符串。

For example, if the input string is 'laptop' and the chosen index value is, say, 3, the string is broken as 'lap' + 'top'. 例如,如果输入字符串为“ laptop”,并且所选索引值为3,则该字符串将被打断为“ lap” +“ top”。 'top' would then be reversed to 'pot' and would be concatenated with the prefix (in the order) as 'pot' + 'lap' 然后将“ top”反转为“ pot”,并将其与前缀(按顺序)连接为“ pot” +“ lap”

The assignment is somewhat confusing and since I'm a novice with little to no experience besides a couple of days working in Python, I'm a little confused as to what to do. 这项任务有些令人困惑,并且由于我是新手,除了在Python中工作几天外,几乎没有经验,所以我对做什么感到困惑。 I'm pretty sure I have to use the slice and concatenation operators but I'm not sure how I should go about constructing a function that suits the above criteria. 我很确定我必须使用slice和串联运算符,但是我不确定应该如何构造适合上述条件的函数。 Any pointers? 有指针吗?

Something like: 就像是:

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

Combining the other two answers, and implementing your reverse function: 结合其他两个答案,并实现反向功能:

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

As a beginner, it helps to step through line by line, or doing tests using the interpreter to see exactly what's going on :) 作为初学者,它有助于一步一步地进行操作,或者使用解释器进行测试以查看发生了什么事:)

You could do as follows: 您可以执行以下操作:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM