首頁  >  文章  >  後端開發  >  Python程式:將字串的第K個索引字連接起來

Python程式:將字串的第K個索引字連接起來

PHPz
PHPz轉載
2023-09-23 18:09:05967瀏覽

Python程式:將字串的第K個索引字連接起來

字串是不可變的資料結構,以字串格式儲存資料。它可以透過使用str()方法或在單引號或雙引號中給出資料來建立。它存取我們使用索引的字串的元素。在索引中,我們有負索引和正索引,與負索引一樣,我們將使用 -1 和 (-string 的長度) 存取最後一個元素到第一個元素。在正索引中,我們將為第一個元素賦予 0,為最後一個元素賦予 (字串長度 - 1)

現在,在本文中,我們將使用 Python 中可用的不同方法來連接字串的第 K 個索引詞。讓我們詳細了解每種方法。

使用循環

在這個方法中,我們使用 split() 方法將輸入字串拆分為單字清單。然後,我們迭代單字並檢查索引是否是 k 的倍數。如果是,我們將帶有空格的單字連接到結果字串。最後,我們使用 strip() 方法從結果字串中刪除所有前導或尾隨空格。

範例

def concatenate_kth_words(string, k):
   words = string.split()  
   result = ""
   for i in range(len(words)):
      if i % k == 0: 
         result += words[i] + " "
      return result.strip()  
my_string = "This is a sample string to test the program"
k = 2
concatenated_words = concatenate_kth_words(my_string, k)
print(concatenated_words)

輸出

This

使用列表推導和join()函數

在這種方法中,我們使用列表理解來建立一個新列表,其中僅包含索引為 k 倍數的單字。然後,我們使用 join() 方法將新清單的元素連接成單一字串,並用空格分隔它們。

範例

def concatenate_kth_words(string, k):
   words = string.split()  
   result = " ".join([words[i] for i in range(len(words)) if i % k == 0])
   return result
my_string = "This is a sample string to test the program"
k = 2
concatenated_words = concatenate_kth_words(my_string, k)
print(concatenated_words)

輸出

This a string test program

使用切片和join()函數

在這個方法中,我們使用列表切片來提取索引為k的倍數的單字。切片words[::k]從第一個元素開始,選擇每個第k個元素。然後我們使用join()方法將選定的單字連接成一個字串,並用空格分隔。

範例

def concatenate_kth_words(string, k):
   words = string.split()  # Split the string into a list of words
   result = " ".join(words[::k])
   return result
my_string = "This is a sample string to test the program"
k = 2
concatenated_words = concatenate_kth_words(my_string, k)
print(concatenated_words)

輸出

This a string test program

以上是Python程式:將字串的第K個索引字連接起來的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除