簡體   English   中英

如何在某些索引處反轉和連接字符串?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM