我想在python中使用for循环来形成一个长句。我有来自sys.stdin的数据,我想用来自stdin的单词组成一个长句。
例如,假设sys.stdin中的cam是
hello
to
all
developers
我当前的程序读作:
word = ''
for k in sys.stdin:
sentence = word + ',' + k
print(sentence)
我也尝试过这种方法:
for k in sys.stdin:
word = ''
sentence = word + ',' + k
print(sentence)
以上所有代码都给了我输出;
,hello
,to
,all
,developers
但我需要一个输出作为;
hello,to,all,developers
请注意;我需要循环中的变量"句子",因为它稍后会在循环中重复使用。
请帮忙吗?感谢您的意见。
不太熟悉python中的for循环,但也许您可以尝试将;print(语句"在for循环之外,因为print((总是要生成一个新行
试试这个
word = ''
for k in sys.stdin:
word = word + ',' + k
print(word)
您需要修改word
,每次在循环内创建另一个变量
sentence = ','.join(k for k in sys.stdin)
试试这个
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
我的方法包含其他答案所缺少的一个关键步骤,即从sys.stdin
输入中删除换行符"n"
。当您尝试这个代码片段时,您将在一行中得到输出。
您可以使用您的方法
word = ''
for k in sys.stdin:
sentence = word + ',' + k
print(sentence)
只需添加
sentence = sentence.replace('n','')[1:]
环路后