您的位置:首页 > 编程语言 > Python开发

python3对一个字符串中长度大于某个值的串倒序,小于某个值不变,最终输出

2020-08-18 16:42 645 查看
a="ecnetnes a si ecnetnes sihT"
lenth=len(a)
print(len(a))
b=[]
c=[]
for i in range(lenth):
if a[i]==" ":
b.append(i)#定位出空格所在位置前一个字符位置
b.append(lenth)
print(b)
for j in b:
if j==b[0]:
if j>=5:
temp1=a[:j][::-1]#前闭后开,不包含空格
else:
temp1=a[:j]
c = temp1
elif j!=b[-1]:
d=j-b[b.index(j)-1]-1
if d>=5:
temp2=a[b[b.index(j)-1]+1:j+1][::-1]#需要颠倒的,包含右边的空格
else:
temp2 = a[b[b.index(j) - 1]:j]#包含左边的空格
#最后一个空格
c=c+temp2
else:
d=j-b[b.index(j)-1]-1
if d>=5:
temp3=a[b[b.index(j)-1]+1:j][::-1]
print(temp3)
temp3=" "+temp3#需添加空格
else:
temp3=a[b[b.index(j)-1]:j]#包含左边的空格
c=c+temp3
print(c)

运行结果:D:\anaconda3\python.exe D:/python/GAN-1D-master/9.py
27
[8, 10, 13, 22, 27]
sentence a si sentence sihT

Process finished with exit code 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐