卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章21403本站已运行3414

Python程序:将字符串的第K个索引单词连接起来

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
卓越飞翔博客
上一篇: 将相同索引字符的交换次数最小化,使得两个字符串中字符的ASCII值之和为奇数
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏