如何在 Python 中反轉字串子音而不影響其他元素


字串子音是指在發音一系列字元或字母時產生的非母音音。在本文中,我們將學習如何使用 Python 中的以下兩種方法,僅反轉字串中的子音而不影響其他元素的位置。

  • 使用 append() 和 join() 函式

  • 使用 pop() 函式和字串連線

示例

Before Reversing : tutorialspoint
After Reversing: tunopiaslroitt

演算法(步驟)

以下是執行所需任務的演算法/步驟。

  • 定義函式 checkConsonant(char) 以檢查字元是否為子音。如果字元不在母音列表(['a', 'e', 'i', 'o', 'u'])中,則返回 True,否則返回 False。

  • 定義函式 consonantReversing(inputString) 以反轉輸入字串中的子音。

  • 使用 list(inputString) 將輸入字串轉換為字元列表。

  • 建立一個空列表 consonantsList 用於儲存子音。

  • 使用 for 迴圈遍歷字元列表。對於每個字元,呼叫 checkConsonant(char) 函式以檢查它是否為子音。如果它是子音,則將其附加到 consonantsList 中。

  • 將變數 l 設定為 consonantsList 的長度減 1。

  • 開始替換輸入字串中的子音。對於列表中的每個字元,如果它是子音(使用 checkConsonant() 檢查),則使用索引 l 用 consonantsList 中相應的子音替換它。然後,l 減 1。

  • 最後,使用 "".join(new_list) 將修改後的字元列表重新連線成字串,並將其作為結果返回。

  • 使用不同的輸入字串兩次呼叫 consonantReversing() 函式以演示子音的替換。

使用 append() 和 join() 函式

以下程式碼包含一個名為 consonantReversing 的函式,該函式以字串作為輸入,並反轉字串中的子音,同時保持母音不變。它透過識別輸入字串中的子音,將它們儲存在一個列表中,然後以相反的順序用列表中的子音替換字串中的子音來實現這一點。然後將修改後的字串作為輸出返回。

示例

# creating a function that checks if the string character
# is consonant or not 
def checkConsonant(char):
  # list of vowels
    vowels = ['a', 'e', 'i', 'o', 'u']

    # checking whether the character is not in vowels
    if char not in vowels:
        # returning true, if the condition is true
        return True
  # else returning false
    return False

# creating another function that reverses the consonants of the string
def consonantReversing(inputString):

    # converting the input string into list of characters
    new_list = list(inputString)

    # creating an empty list for storing consonants
    consonantsList = []
    # traversing through the above list of characters
    for char in new_list:
        # checking if the current character is a consonant
        # by calling the checkConsonant function
        if checkConsonant(char):
          # appending that character to the consonants list
          # if the condition is true
            consonantsList.append(char)
    l = len(consonantsList)-1

    # Substitute the consonants within a provided string by replacing them with elements
    # from a consonant list, starting from the last element in the list.
    for m in range(len(new_list)):
        if checkConsonant(new_list[m]):
            new_list[m] = consonantsList[l]
            l -= 1
    return "".join(new_list)

# calling the above consonantReversing() function by
# passing the input string as an argument to it.
print(consonantReversing("tutorialspoint"))
# checking for the other string
print(consonantReversing("python codes"))

輸出

執行上述程式後,將生成以下輸出

tunopiaslroitt
sdc onhtoyep

使用 pop() 函式和字串連線

在以下示例中,替代方法在遍歷字串時直接識別輸入字串中的子音,而無需使用其他函式。它將子音儲存在一個列表中,並在第二次迭代期間以相反的順序替換它們。其餘字元,包括非子音,按原樣附加到輸出字串。

示例

def consonantReversing(inputString):
    consonants = [c for c in inputString if c.lower() in 'bcdfghjklmnpqrstvwxyz']
    outputString = ""
    
    for char in inputString:
        if char.lower() in 'bcdfghjklmnpqrstvwxyz':
            outputString += consonants.pop()
        else:
            outputString += char
    
    return outputString

# Example usage:
print(consonantReversing("tutorialspoint"))
print(consonantReversing("python codes"))

輸出

tunopiaslroitt
sdcnoh toyep

結論

總之,提供的 Python 程式成功地反轉了給定字串中的子音,而不影響其他元素的位置。它採用兩種不同的方法:一種使用 append() 和 join() 函式,另一種使用 pop() 函式和字串連線。這兩種方法都有效地識別和反轉子音,同時保留字串中的母音和其他字元。這些方法提供了靈活性,可以應用於需要子音反轉的各種場景。

更新於: 2023年8月17日

222 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.