-1

How to reverse words in string in python using for loop? EX- "HELLO WORLD" to "WORLD HELLO"

str="HELLO WORLD"

Ashwin Geet D'Sa
  • 4,682
  • 22
  • 48
Nihar Ranjan
  • 9
  • 1
  • 1

7 Answers7

1

I'm coming up with a comprehensive answer:

Here's what you want, just bare* python constructs:

input = 'Hello'
word = ' '
output = ''
for c in input:
    if c == ' ':
        output = word + output
        word = ' '
    else:
        word += c
output = word[1:] + output

It's just iterating over all letters and keeps them until a word is built. When current character c is a space, it prepends current word to the output string. After the for-loop there's a need to prepend the last word to output. It has to be done manually since there's no whitespace at the end of a string you provided. word[1:] just removes and extra space from the last word.

But the above solution isn't really effective since many string creations and concatenations are used. If you want to create a compact and pythonic solution, here's one:

input = "Hello world"
output = ' '.join(reversed(input.split()))
  1. input.split() turns input into a list ['Hello', 'world']

  2. reversed(...) turns the list into ['world', 'Hello']

  3. ' '.join(...) concatenates each string in the list ['world', 'Hello'] with a space between each pair of words, so the result is 'world Hello'.

Quick and dirty, isn't it?

*bare - what OP claimed as without using any internal function

asikorski
  • 779
  • 4
  • 16
  • 2
    Given Python's core tenet of "batteries included", why is this regarded as more "pure" than using the standard methods of the built in types? It's just a preference for syntax and symbols over names, at the cost of both execution efficiency and legibility. It makes sense only in a tutorial context, where only a few mechanisms have been introduced. I don't think even DrPython performs such restrictions (while DrRacket does with language levels). I understand this is not your confusion, asikorski, but I had the impulse to rant a bit. – Yann Vernier Jul 27 '19 at 12:27
  • With *pure* I meant what OP claimed in comments as *without using any internal function*. To be honest, I didn't think of that *pure* might sound misleading but I see your point. Changed *pure* to *bare*. – asikorski Jul 27 '19 at 12:39
  • After some additional reading, the Python language reference does define sufficient details to make this not rely on the standard library documentation, and notes this as "core semantics". So there does exist such a boundary. – Yann Vernier Jul 27 '19 at 12:47
0
' '.join(str.split(" ")[-1::-1]) 

output:

WORLD HELLO

With for-loop

outputLst =[]

words = str.split(" ")
for word in words:   
    outputLst.insert(0, word)
' '.join(outputLst)

output:

`WORLD HELLO`
frankegoesdown
  • 1,876
  • 1
  • 15
  • 36
  • without using any internal function, using only for loop can u plz help me to slove this one. – Nihar Ranjan Jul 27 '19 at 11:38
  • *If you're prepending many elements to the list, you're doing it wrong.* – asikorski Jul 27 '19 at 12:58
  • I actually meant that using `.insert(0, word)` is simply non-effective since prepending item to a list is a high-cost operation, especially when the list is long. It is better to use `reversed` to iterate over `words` and append each word to the `outputLst`. – asikorski Jul 27 '19 at 13:25
0

You don't need a for-loop for that: just use the position of the space-character, as you can see in following pseudo-code:

int i_space = location(" ", "HELLO WORLD"")
result = substring("HELLO WORLD", 1, i_space - 1) + " " + substring("HELLO WORLD", i_space + 1, Length("HELLO WORLD"))

A for-loop is more useful for handling more elaborate cases, like:

HELLO THIS IS A BEAUTIFUL WORLD => transfer into:
WORLD BEAUTIFUL A IS THIS HELLO

Or:

HELLO WORLD => transfer into:
DLROW OLLEH

Does this answer your question?

Dominique
  • 13,061
  • 14
  • 45
  • 83
0
str="HELLO WORLD"
rev=""
for i in range(len(str.split(" "))):
    rev=str.split(" ")[i]+" "+rev

Output: WORLD HELLO

Another solution for not using the builtin function:

def split(str):
    list_str=[]
    j=0;
    for i in range(len(str)):
        if str[i]==' ':
            list_str.append(str[j:i])
            j=i+1;
    list_str.append(str[j:i+1])
    return list_str


str="HELLO WORLD"
rev=""
list_str=split(str)
for i in range(len(list_str)):
    rev=list_str[i]+" "+rev
print(rev)

Output: WORLD HELLO

Ashwin Geet D'Sa
  • 4,682
  • 22
  • 48
0

a gentle progression of solutions:

first, the naive one:

text = 'hello world'

words = text.split()  # words = ['hello', 'world']
line = []
for i in range(len(words), 0, -1):  # iterate i over [2, 1]
    line.append(words[i - 1])  # append 'hello' then 'world' to line
print(' '.join(line))  # join the contents of line together with spaces and print

next we use the reversed iterator:

words = text.split()
line = []
for i in reversed(range(len(words))):
    line.append(words[i])
print(' '.join(line))

next we use the list iterator:

words = text.split()
line = []
for word in reversed(words):
    line.append(word)
print(' '.join(line))

finally, we do everything with an implicit loop:

print(' '.join(reversed(text.split())))
Sam Mason
  • 12,674
  • 1
  • 33
  • 48
  • text = 'hello world' words = text.split() line = [] for i in range(len(words), 0, -1): line.append(words[i - 1]) print(' '.join(line)) – Nihar Ranjan Jul 29 '19 at 07:56
  • I've added some comments, not sure if that helps as they're just doing what the code says. I'd suggest you add lots of `print` statements to the code, or run it line-by-line interactively and just check the values of the variables after you paste the next line in – Sam Mason Jul 29 '19 at 10:59
0

One version just with loops, without any function:

s = 'Hello  World, this string will be reversed!'

def reverse_words(s):
    rv = ''
    buf = ''
    for ch in s[::-1]:
        if ch != ' ':
            buf += ch
        else:
            if buf:
                rv += buf[::-1] + ' '
            buf = ''
    if buf:
        rv += buf[::-1]

    return rv

s = reverse_words(s)
print(s)

Prints:

reversed! be will string this World, Hello
Andrej Kesely
  • 118,151
  • 13
  • 38
  • 75
0

I started learning python recently and this is something which i tried

name=input("Enter the word you want the reverse :")
a=(len(name))
print(a)
for i in range (1,a+1):

    print("{}".format(name[-i]),end="")
Nikhil
  • 1
  • 1