【发布时间】:2016-11-25 22:19:42
【问题描述】:
试图解决我可以反转字符串中每个单词的问题,由于与 C 不同,python 中没有“\0”,所以我的逻辑是无法拾取字符串的最后一个字符。 知道如何在不对代码进行太多更改的情况下解决此问题
Input = This is an example
Output = sihT si na elpmaxe
import os
import string
a = "This is an example"
temp=[]
store=[]
print(a)
x=0
while (x <= len(a)-1):
if ((a[x] != " ") and (x != len(a)-1)):
temp.append(a[x])
x += 1
else:
temp.reverse()
store.extend(temp)
store.append(' ')
del temp[:]
x += 1
str1 = ''.join(store)
print (str1)
我的输出是截断最后一个字符
sihT si na lpmaxe
【问题讨论】:
-
您的条件明确排除了最后一个字符。
-
你写 c 的时间太长了。
print ' '.join(word[::-1] for word in a.split()) -
@pvg 如果我这样做:如果 ((a[x] != " ") and (x != len(a))) 我的输出完全截断了最后一个单词。输出是:sihT si na
-
@pvg 和 while 循环,如果我这样做:while (x
-
目前尚不清楚您为什么不想更改代码,但正如@Holloway 所展示的,您尝试做的事情可以在一条短线中以 Python 方式完成。有理由维护您的代码吗?