单词反转 python

发布于:2024-03-28 ⋅ 阅读:(20) ⋅ 点赞:(0)

#给定—个字符串,逐个翻转字符串中的每个单 词
#输入: " the sky is blue",
#输出: "blue is sky the "

#翻转后,空格不能减少,单词之间的空格数量不能发生变化

def reverse_word(string):
	# 先将整个句子翻转
	word_lst = list(string)  # 转换成列表
	for i in range(len(word_lst) // 2):
		word_lst[i], word_lst[len(word_lst) - 1 - i] = word_lst[len(word_lst) - 1 - i], word_lst[i]  # 进行反转
	
	# 翻转里面的单词
	start_index = None
	end_index = None
	b_word = False
	for index, item in enumerate(word_lst):
		if item.isalpha():  # 如果是字母
			if not b_word:  # 如果为假 说明是单词的第一个字母
				start_index = index
				b_word = True
		else:  # 不是字母
			if b_word:  # 不是字母 并且为真 说明是空格
				end_index = index - 1  # 最后一个单词的结束位置
				b_word = False
				# 已经知道单词开始和结束的位置,翻转这个单词
				reverse_single_word(word_lst, start_index, end_index)
			
			# 检查循环结束后是否还有未处理的单词
	if b_word:
		end_index = len(word_lst) - 1  # 最后一个单词的结束位置是列表的最后一个元素
		reverse_single_word(word_lst, start_index, end_index)
	
	return "".join(word_lst)


def reverse_single_word(lst, start_index, end_index):
	while start_index < end_index:
		lst[start_index], lst[end_index] = lst[end_index], lst[start_index]
		start_index += 1
		end_index -= 1


if __name__ == '__main__':
	string = ' the sky is   blue'
	print(reverse_word(string))

首先将字符串转换成列表 再把列表中的每个元素反转
然后再拼接成字符串
这样 字符反转了 并且空格也被存储在列表中 空格也被反转了

再接着 提取单词 反转单词就行
提取单词和前面的一样 在单独写个反转列表的方法就行

本文含有隐藏内容,请 开通VIP 后查看