Python程式:連線字串中第K個索引的單詞


字串是不可變的資料結構,它以字串格式儲存資料。可以使用str()方法或用單引號或雙引號括起來的資料來建立它。訪問字串的元素,我們使用索引。在索引中,我們有負索引和正索引,在負索引中,我們將使用-1和(-字串長度)來訪問最後一個元素到第一個元素。在正索引中,我們將為第一個元素賦予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

更新於:2023年8月2日

84 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告