0

I need to write a function that takes a string as an argument and outputs the letters backward, one per line.so far I have this:

def wordReverse(word):
	acum = ""
	for ch in word:
		acum = ch + acum
	return acum

I tried adding \n to acum but an error occurs.Where should I put it?

4
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by pyTony
Featured Replies
  • nevermind. I got it. here's what I did: [code] def wordReverse(word): acum = "" for ch in word: acum= ((ch)+"\n") + acum print acum [/code] Read More

1

nevermind. I got it. here's what I did:

def wordReverse(word):
	acum = ""
	for ch in word:
		acum= ((ch)+"\n") + acum
	print acum
0
def wordReverseToLines(word):
  for i in range(len(word)-1,-1,-1):
    print (word[i])
# or
def wordReverseUsingList(word):
  arr = [x for x in word]
  arr.reverse()
  print ("\n".join(arr))

Edited by griswolf: n/a

0

nevermind. I got it. here's what I did:

def wordReverse(word):
	acum = ""
	for ch in word:
		acum= ((ch)+"\n") + acum
	print acum

Great, very nice solution!

You can use Python built-in functions to simplify it a little ...

def wordReverse(word):
    for ch in reversed(word):
        print ch

wordReverse("python")

Edited by vegaseat: show off

0

And for the beauty of recursion you can try:

def wordReverse(word):
    if not word:
        return word ## empty sequence is already reversed
    else:
        return word[-1]+wordReverse(word[:-1])

print wordReverse('Python newbie')

And the classic "vegaseat's"

def wordReverse(word):
    return word[::-1] # -1 step from default start to default end

Edited by pyTony: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.