python基础入门——字符串按单词反转

字符串按单词反转(必须保留全部空格)

def reverse(str_list, start, end):
    while start < end:
        str_list[start], str_list[end] = str_list[end], str_list[start]
        start += 1
        end -= 1

setence = ' Hello, how are you?   Fine.   '
str_list = list(setence)
# print(setence)
# print(str_list)
i = 0
while i < len(str_list):
    if str_list[i] != ' ':
        start = i
        end = start + 1
        while (end < len(str_list)) and str_list[end] != ' ':
            end += 1
        reverse(str_list, start, end - 1)
        i = end
    else:
        i += 1
str_list.reverse()
# print(str_list)
print(''.join(str_list))


函数的定义:先定义一个列表的反转函数,在python中,两者快速交换,用    a, b = b, a

输入要反转的句子

 Hello, how are you?   Fine. 

将句子转换成为列表

[' ', 'H', 'e', 'l', 'l', 'o', ',', ' ', 'h', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u', '?', ' ', ' ', ' ', 'F', 'i', 'n', 'e', '.', ' ', ' ', ' ']

之后对列表进行反转,保留空格

[' ', ' ', ' ', 'F', 'i', 'n', 'e', '.', ' ', ' ', ' ', 'y', 'o', 'u', '?', ' ', 'a', 'r', 'e', ' ', 'h', 'o', 'w', ' ', 'H', 'e', 'l', 'l', 'o', ',', ' ']

最后将其进行整体的反转,从而实现句子反转,且保留原有空格

   Fine.   you? are how Hello, 

 

 

 

你可能感兴趣的:(python基础)