简体   繁体   中英

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'. 'top' would then be reversed to 'pot' and would be concatenated with the prefix (in the order) as '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. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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