Home > Blockchain >  Build a long string from words in a For Loop
Build a long string from words in a For Loop

Time:10-11

I would like to form a long sentence using a for loop in python. I have data that came from sys.stdin and i would like to form a long sentence from the words that came from stdin.

For example,assume the words that cam from sys.stdin were

hello
to
all
developers

My current program reads as:

word = ''
for k in sys.stdin:
  sentence = word   ','   k
  print(sentence)

I have also tried this approach:

for k in sys.stdin:
   word = ''
   sentence = word   ','   k
   print(sentence)

All the above codes gives me the output;

,hello
,to
,all
,developers

But I need an output as;

hello,to,all,developers

Please Note; I NEED THE VARIABLE 'sentence' INSIDE THE LOOP BECAUSE IT WILL BE RE-USED IN THE LOOP LATER.

Any help please? Thank you for your input.

CodePudding user response:

Not as familiar with for loops in python, but maybe you could try putting the "print(sentence" outside of the for loop, because print() is always going to make a new line

CodePudding user response:

Try this

word = ''
for k in sys.stdin:
  word = word   ','   k
print(word)

You need to modify word, you were creating another variable each time inside the loop

CodePudding user response:

sentence = ','.join(k for k in sys.stdin)

CodePudding user response:

Try this

import sys

sentence = []
for k in sys.stdin:
    if "\n" in k: # sys.stdin input contains newlines, remove those first
        sentence.append(k[:-1]) # removes the \n (newline literal) before adding to sentence list
    else:
        sentence.append(k)

print(",".join(sentence)) # converts the list of words into one long string separated with commas

My approach to this contains one key step that other answers are missing, which is removing the newline "\n" from sys.stdin input. When you try this code snippet, you'll get your output in one line.

CodePudding user response:

You can use your approach

word = ''
for k in sys.stdin:
  sentence = word   ','   k
  print(sentence)

just add

sentence = sentence.replace('\n','')[1:]

after the loop

  • Related