如何在Python中提取字符串每隔一个单词并反转以生成目标字符串?
解决方案
步骤说明
- 先将原字符串按空格分割成单词列表,你之前用
list(mystr)是错误的,这会把每个字符单独拆出来,而非按单词拆分。 - 遍历单词列表,对索引为奇数的单词(也就是第2、4、6个单词,Python索引从0开始)进行反转。
- 最后将处理后的单词列表重新拼接成字符串。
实现代码
mystr = 'one two three four five six' # 按空格分割成单词列表 word_list = mystr.split() # 遍历列表,处理目标单词 for i in range(len(word_list)): # 对索引为奇数的单词执行反转操作 if i % 2 == 1: word_list[i] = word_list[i][::-1] # 拼接成最终目标字符串 result = ' '.join(word_list) print(result) # 输出: one owt three ruof five xis
单独提取每隔一个单词的方法
如果只是需要先提取第2、4、6个单词,可直接通过切片实现:
mystr = 'one two three four five six' word_list = mystr.split() target_words = word_list[1::2] # 从索引1开始,步长为2取元素 print(' '.join(target_words)) # 输出: two four six
内容的提问来源于stack exchange,提问作者Pratik Bawane
相关产品推荐
相关产品推荐

