How to reverse words in string in python using for loop? EX- "HELLO WORLD" to "WORLD HELLO"
str="HELLO WORLD"
How to reverse words in string in python using for loop? EX- "HELLO WORLD" to "WORLD HELLO"
str="HELLO WORLD"
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()))
input.split() turns input into a list ['Hello', 'world']
reversed(...) turns the list into ['world', 'Hello']
' '.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
' '.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`
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?
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
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())))
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
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="")