本文主要是介绍python实现句子倒叙,且保留原始空格数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
"""
完成一个句子的倒叙,单词中的字母顺序不变
输入: 输出:
’ 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 ")
这篇关于python实现句子倒叙,且保留原始空格数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!