python实现句子倒叙,且保留原始空格数

"""
完成一个句子的倒叙,单词中的字母顺序不变
输入: 输出:
1 1
’ 1‘ ’1 ‘
...
"""
def revers_str(str_old):
l_s = list(str_old) #string 转list
a = len(l_s)
newStr = ''
newTab = ''
newList = []
str_new = ''
for i in range(a):
if l_s[i] != ' ': #空格串不为空则添加到数组,重置空格串为空,判断元素为字母并且拼接
if newTab != '':
newList.append(newTab)
newTab = ''
newStr += l_s[i]
else:#单词串不为空则添加到数组,重置单词串为空,判断元素为空格并且拼接
if newStr != '':
newList.append(newStr)
newStr = ''
newTab += l_s[i]
if i == a-1:
if newTab != '':
newList.append(newTab)
else:
newList.append(newStr)

newList.reverse()
for str in newList:
str_new += str
print(str_new)

revers_str(" 13E 2RRRV 3RRR ")

posted on 2022-06-04 02:17  Darren-Frank  阅读(99)  评论(0)    收藏  举报

导航