字符串问题python实现(四)

问题:将一句话里的单词进行倒置,标点符号不转换。比如一句话"i come from tianjin."倒换后变成"tianjin.from come i"。

python版代码:

# -*- coding:utf-8 -*-
# 问题:将一句话里的单词进行倒置,标点符号不转换。
#      比如一句话"i come from tianjin."倒换后变成"tianjin.from come i"。
# by chasdmeng

def Strinver(string):
    stra = list(string)
    i = 0
    j = len(stra)-1
    while i < j:
        temp = stra[i]
        stra[i] = stra[j]
        stra[j] = temp
        i +=1
        j -=1
    i = 0
    while i < len(stra):
        if stra[i] != ' ':
            begin = i
            while i !=len(stra) and stra[i] != ' ':
                i +=1
            i -=1 #注意
            end = i
        while begin < end:
            temp = stra[begin]
            stra[begin] = stra[end]
            stra[end] = temp
            begin +=1
            end -=1
        i +=1 #不这样写会出现无法继续执行while循环
    return ''.join(stra)
if __name__ == '__main__':
    string = "i come from tianjin."
    print string

    print Strinver(string)

你可能感兴趣的:(Python)