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

PHPz
发布: 2023-09-23 18:09:05
转载
992 人浏览过

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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!