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?

Dani AI

Generated

A few clarifying points that build on what , , and showed:

Prepending characters (the ch + acum pattern) copies the whole string on every loop iteration, so it runs in quadratic time and becomes noticeably slow for long inputs. Also, putting "\n" in front of the accumulating string changes where the first printed character appears; it’s easy to get the order or an extra leading/trailing newline wrong.

Prefer separating concerns: have the function return a value (a single string or an iterator) rather than printing directly. That makes the function reusable (tests, logging, further processing) and avoids forcing I/O behavior on callers. If you need efficiency and want a single string with one character per line, build the pieces and join once rather than repeatedly concatenating.

An efficient, alternative implementation using a deque (avoids repeated copies while keeping code clear):

from collections import deque

def word_reverse_lines(word):
    d = deque()
    for ch in word:
        d.appendleft(ch)     # O(1) per operation
    return "\n".join(d)

Notes and edge cases: for streaming very large inputs, consider yielding each reversed character instead of returning one huge string. On Python 3 use print(...); on legacy Python 2 be explicit about unicode vs str when non-ASCII characters may appear. Always test the empty-string case and confirm whether you want a trailing newline — join produces no trailing newline (add one explicitly if needed).

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

def wordReverse(word):
	acum = ""
	for ch in word:
		acum= ((ch)+"\n") + acum
	print acum
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))

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")

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.