What is the pythonic way to doing this?
From this: 'This is a string to try' to this: 'try to string a is This'
My first guess was:
for w in 'This is a string to try'.split(' ')[::-1]:
print w,
but str.split() is not allowed. Then I came up with this:
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]
If string.partition is allowed as a replacement:
otherwise fallback on string.find:
Use re
In some interviews you're constrained when using Python, e.g. don't use
reversed
,[::-1]
, or.split()
.In those cases, the following code in
Python 2.7
can work (adopted from Darthfett's answer above):One liner (except for the 'import re' bit) as requested:
Edit: well, if
str.split
were allowed, it would be this ;-) Alternatively, you could write your own version of split of course.There are three steps: split by space, reverse the list with words and concatenate the list of strings to one string with spaces in between.