如何在 Python 中獲取字串的後 N 個字元


字串操作是 Python 中一項重要的任務。這可能涉及切片字串、獲取 N 個字元等。這些是在文字預處理中必不可少的任務,例如在 NLP 任務、密碼和資料安全、字串理解和編碼等中。幸運的是,Python 提供了多種執行字串操作的方法。在本文中,我們將學習如何在 Python 中獲取字串中的後 N 個字元。

使用 for 迴圈

迴圈是大多數程式語言中非常常見的表示式。這使我們能夠迭代可迭代物件、生成一系列值等等。由於字串物件是可迭代的,我們可以利用 for 迴圈來獲取字串的後 n 個字元。由於可迭代物件的索引從 0 開始,結束並擴充套件到 length−1,因此字串後 n 個字元的索引是從 length−n−1 到 length−1。

示例

在下面的示例中,我們建立了一個名為 get_last_n_characters 的函式,它將字串和 n 作為引數。它是一個非空函式,並返回字串的後 n 個字元。在函式下,我們聲明瞭一個名為 last_n_characters 的空字串,並使用 range 表示式迭代字串的後 n 個字元。我們將字串的字元追加到空字串中,並返回最終字串。

def get_last_n_characters(text, n):
    last_n_characters=""
    for i in range(len(text) - 1, len(text) - n - 1, -1):
        last_n_characters = text[i] + last_n_characters
    return last_n_characters
text = "Hello, world!"
n = 5
result = get_last_n_characters(text, n)
print(f"The last {n} characters of the String are: {result}")

輸出

The last 5 characters of the String are: orld!

使用 while 迴圈

while 迴圈是 Python 中另一個流行的表示式,就像 for 迴圈一樣。但是,唯一的區別是我們需要在需要弄清楚需要執行迴圈多少次時使用 while 迴圈。當我們滿足特定條件時,我們就完成迴圈。

示例

在下面的程式碼中,我們建立了函式 get_last_n_characters。在這個函式下,我們初始化了一個空字串。我們透過 while 迴圈迭代字串的後 n 個字元,並在每次迭代中,我們將字元追加到已初始化的字串中。

def get_last_n_characters(text, n):
    last_n_characters = ""
    index = len(text) - 1
    while n > 0 and index >= 0:
        last_n_characters = text[index] + last_n_characters
        index -= 1
        n -= 1
    return last_n_characters

text = "Hello, world!"
n = 9
result = get_last_n_characters(text, n)
print(f"The last {n} characters of the string are: {result}")

輸出

The last 9 characters of the string are: o, world!

使用字串切片

切片字串是在大多數程式語言中一個重要的概念。在 Python 中,切片使用索引屬性的概念。

語法

string[a:b]

這裡 string 是字串物件的名稱。這裡的 a 指的是我們需要開始切片的索引,b 是我們需要切片的索引。請注意,a 是包含的,但 b 是不包含的。如果我們不指定,Pyon 將預設值為 0。另一方面,如果我們不指定 b,則 Python 將 b 的預設值設定為 n。

示例

在下面的程式碼中,我們使用了字串的內建方法來訪問後 n 個字元。我們使用了字串切片,其中我們傳遞了 -n 作為起始索引,並預設作為結束索引。因此,作為索引屬性,該方法會切片字串並返回字串的後 n 個字元。

def get_last_n_characters(string, n):
    last_n_characters = string[-n:]
    return last_n_characters
text = "Hello, world!"
n = 5
result = get_last_n_characters(text, n)
print(f"The last {n} characters of the String are: {result}")

輸出

The last 5 characters of the String are orld!

使用切片方法

切片方法允許您建立一個切片物件,您可以使用它來提取序列的一部分。我們可以將此切片物件傳遞給字串,返回所需的字元。

語法

slice(-start, end)

這裡 slice 是一個關鍵字,也是 Python 中的內建方法。-start 表示我們希望從索引為 -start 的字元開始切片字串。end 指的是我們需要執行切片的索引。由於我們指定了 None,因此我們將對字串的最後一個字元進行切片。

示例

在下面的程式碼中,我們使用了 Python 的 slice 方法來獲取字串的後 n 個字元。我們將第一個引數(即起始索引)定義為 -n,表示我們希望從字串的後 n 個字元開始切片。我們將結束索引的值設定為 None,表示我們希望切片到最後一個字元。

def get_last_n_characters(string, n):
    last_n_characters = slice(-n, None)
    return string[last_n_characters]

text = "Hello, world!"
n = 5
result = get_last_n_characters(text, n)
print(f"Last {n} characters of the String is: {result}")

輸出

Last 5 characters of the String is: orld!

使用 join 和 reversed 方法

在 Python 中,join() 和 reversed() 方法通常用於操作字串和序列。

join() 方法是一個字串方法,它將可迭代物件(例如列表或元組)的元素連線成一個字串。它以可迭代物件作為引數,並返回一個新的字串,該字串使用指定的分割符連線元素。

語法

new_string = separator.join(iterable)

這裡 new_string 是連線元素後生成的字串。separator 是用作元素之間分隔符的字串。iterable 是包含要連線的元素的可迭代物件。

reversed() 方法是 Python 中的內建函式,它返回一個迭代器,該迭代器按相反順序生成序列的元素。它可以與字串、列表、元組或任何其他序列型別一起使用。

語法

reversed_sequence = reversed(sequence)

這裡 reversed_sequence 是一個迭代器物件,包含按相反順序排列的序列元素。sequence 是獲取反向元素的序列。

示例

我們在下面的程式碼中結合了 joined、reversed 和索引屬性來獲取後 n 個字元。reverse 方法反轉字串,切片方法提取前 n 個字元。再次使用索引方法 "[::-1]",我們反轉了字串。這恢復了字元的原始順序。

def get_last_n_characters(string, n):
    last_n_characters = ''.join(reversed(string))[:n][::-1]
    return last_n_characters
text = "Hello, world. I am testing this message"
n = 6
result = get_last_n_characters(text, n)
print(f"Last {n} characters of the String is: {result}")

輸出

Last 6 characters of the String is: essage

使用 deque 和 join 方法

在 Python 中,join() 方法和 collections 模組中的 deque 類通常用於字串操作和有效管理可迭代物件。

deque 類是 Python 中 collections 模組的一部分,它提供了一個雙端佇列。它允許有效地對佇列的兩端進行新增和刪除元素的操作。它可以用可迭代物件初始化,也可以不帶任何引數初始化。

語法

collections.deque(iterable, maxlen)

這裡 deq 是儲存元素的 deque 物件。iterable 是可選的,其元素將新增到 deque 的可迭代物件。如果未指定,則建立一個空 deque。maxlen 是另一個可選引數,它指定 deque 的最大長度。如果指定,則新增超過此限制的元素將從相反端刪除元素。

透過結合 join() 方法和 deque 類以及指定的 maxlen,例如 join(deque(string, maxlen=n)),您可以有效地提取字串或序列的一部分,同時限制生成連線字串的長度。

示例

在下面的示例中,我們首先從 Python 的 collections 庫中匯入了 deque 方法。接下來,我們使用 deque 方法訪問字串的後 n 個字元。我們將字串和 maxlen=n 作為引數傳遞給字串。我們使用 join 方法將字串連線到空字串。

from collections import deque
def get_last_n_characters(string, n):
    last_n_characters = ''.join(deque(string, maxlen=n))
    return last_n_characters
text = "Hello, world. I am testing this message"
n = 11
result = get_last_n_characters(text, n)
print(f"Last {n} characters of the String is: {result}")

輸出

Last 11 characters of the String is: his message

結論

在本文中,我們學習瞭如何使用不同的內建方法和程式設計技術來獲取字串的後 N 個字元。首先,我們學習瞭如何在 Python 中使用切片操作來獲取字串的後 N 個字元。接下來,我們看到了使用 slice 方法、字串方法和一些內建函式(如 deque)來獲取字串的後 N 個字元。我們強烈建議讀者嘗試這些示例以更好地理解這些主題。

更新於: 2023-07-18

4K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告