Python - 將單詞移到末尾
給定問題需要建立一個 Python 程式,將一個單詞移動到給定字串的末尾。因此,我們將擁有一個 Python 程式碼,藉助它,我們將能夠將單詞移動到指定位置。
理解問題的邏輯
手頭的問題是使用 Python 將一個單詞移動到給定字串的末尾。因此,在本文中,我們將使用兩種方法來執行給定的任務。在第一種方法中,我們將使用 Python 的 replace 方法。在第二種方法中,我們將使用 Python 的 split、append 和 remove 方法。因此,首先我們將定義必須移動單詞的字串,並將該單詞新增到末尾。並將該單詞儲存在一個單獨的變數中,以便我們可以輕鬆地將其從字串中刪除。請參閱下面的示例影像
演算法
步驟 1 − 初始化我們必須對其執行移動操作的字串。使用 input_str 名稱定義它。並將其列印到控制檯。
步驟 2 − 之後,初始化要從字串末尾移動的單詞,並將其命名為 move_str。
步驟 3 − 現在,我們將使用 Python 的 replace 方法替換給定 input_str 中的上述單詞,並將新字串儲存在 after_moving 變數中。
示例
#Code to move word to rear end
# initialize the string
input_str = 'Hello dear friends, You are reading this article on Tutorials Point '
# printing original string
print("Input string is : " + str(input_str))
# initialize the word to move
move_str = 'reading this'
# Move the word to rear end
after_moving = input_str.replace(move_str, "") + str(move_str)
# printing the result after moving the word
print("Output string after moving the word : " + str(after_moving))
輸出
Input string is : Hello dear friends, You are reading this article on Tutorials Point Output string after moving the word : Hello dear friends, You are article on Tutorials Point reading this
演算法 - 另一種方法
步驟 1 − 初始化我們必須對其執行任務的字串,並使用 input_str 名稱定義它。並將此輸入字串列印到控制檯。
步驟 2 − 接下來,初始化要從給定字串末尾移動的單詞,並將其命名為 move_word。
步驟 3 − 現在,使用 split 方法,我們將拆分 input_str 並將其儲存在名為“a”的單獨變數中。
步驟 4 − 並在“a”字串中,我們將使用 Python 的 remove 方法刪除 move_word。
步驟 5 − 之後,我們將使用 append 方法將從字串中刪除的單詞附加到字串中。並使用 join 方法,我們將刪除的單詞加入到 Output 字串中,並使用 Output_str 列印結果。
示例 - 另一種方法
# Code to show the working
# initialize the string
input_str = 'Tutorials Point is best platform for learners '
# printing original string
print("Input String : " + str(input_str))
# initialize the substring
move_word = 'best'
# move the word to rear end
a = input_str.split()
a.remove(move_word)
a.append(move_word)
Output_str = " ".join(a)
# printing the result
print("Output String : " + str(Output_str))
輸出
Input String : Tutorials Point is best platform for learners Output String : Tutorials Point is platform for learners best
複雜度
使用 Python 將單詞移動到末尾的兩種方法的時間複雜度均為 O(1),因為我們對給定字串執行了恆定操作。
結論
正如我們已經成功建立了一個程式,將單詞移動到給定字串的末尾。我們基本上使用了 Python 的一些內建函式。因此,藉助本文,您可以學習 Python 的 replace、join、append、remove 和 split 方法的使用方法。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP