how to merge individual words into one line

61 Views Asked by At

I've done the following:

  1. opened file
  2. split into list
  3. made reverse loop by using for loop
  4. output like below :

# I am interested in position Dualer Master (w/m) im Bereich "Next Generation B2B

B2B
Generation
"Next
Bereich
im
(w/m)
Master
Dualer
position
in
interested
am
I

Now I need to remerge these individual words again into one line, any help?

Below is my code:

fh = open('new.txt', 'r')
for file in fh :
    line = file.split()
    for word in reversed(line):
        print(word)
1

There are 1 best solutions below

0
Sudarshan On

Your code can generate output like:

B2B
Generation
"Next
Bereich
im
(w/m)
Master
Dualer
position
in
interested
am
I

By formatting the print function you can remerge the output. Like

fh = open('new.txt', 'r')
for file in fh :
    line = file.split()
    for word in reversed(line):
        print(word, end=' ')

If you want this as string for reusing, you can join the words. Full code

fh = open('new.txt', 'r')
oneLineString = ''
for file in fh :
    line = file.split()
    for word in reversed(line):
        print(word)
        oneLineString+= (word + " ")
print(oneLineString)

Output:

B2B
Generation
"Next
Bereich
im
(w/m)
Master
Dualer
position
in
interested
am
I
B2B Generation "Next Bereich im (w/m) Master Dualer position in interested am I