执行此操作的 pythonic 方法是什么?
从这个:'This is a string to try'到这个:'try to string a is This'
我的第一个猜测是:
for w in 'This is a string to try'.split(' ')[::-1]:
print w,
但是 str.split() 是不允许的。然后我想出了这个:
def reverse_w(txt):
tmp = []
while (txt.find(' ') >= 0):
tmp.append(txt[:txt.find(' ')])
txt = txt[txt.find(' ')+1:]
if (txt.find(' ') == -1):
tmp.append(txt)
return tmp[::-1]
最佳答案
def reverse(sentence):
sentence = 'This is a string to try'
answer = ''
temp = ''
for char in sentence:
if char != ' ':
temp += char
else:
answer = temp + ' ' + answer
temp = ''
answer = temp + ' ' + answer
return answer.rstrip(' ')
关于python - 在不允许 str.split() 的情况下反转字符串的词序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10745593/