简体   繁体   English

Python 3.x:sys.stdin.readlines()上的''.join()输入在最终字符不是换行/换行符时不返回最终字符串

[英]Python 3.x: ' '.join() on sys.stdin.readlines() Input Does Not Return Final String When Final Character Is Not a Line/Carriage Break

I'd like to convert a chunk of text, be it a single line or multiple lines, into a single string with one remaining white space " " at the end. 我想转换成文本块,无论是单行或多行,到一个单一的字符串一个剩余空格" "结尾。

This is my code: 这是我的代码:

# Take a block of text as input.
print("Input Your Sentence(s) Below (and Then Hit CTRL+D):")
samp_sent = sys.stdin.readlines()

samp_sent = ' '.join(samp_sent)
samp_sent = samp_sent.replace("\n", " ")
print(samp_sent)

If the final character is not a line break, it omits the string and just adds the " " . 如果最后一个字符不是换行符,则它会省略字符串并仅添加" "

Examples (Input → Output): 示例(输入→输出):

  1. "Here is one line. \\n Here is another line. \\n""Here is one line. Here is another line. " "Here is one line. \\n Here is another line. \\n""Here is one line. Here is another line. "

  2. "Here is one line. \\n Here is another line." "Here is one line. " "Here is one line. "

  3. "Here is one line." " " " "

No matter if I type examples (1), (2), or (3) as input, how can I make sure that the final line will always appear in print(samp_sent) ? 无论我输入示例(1),(2)还是(3)作为输入,如何确保最后一行始终出现在print(samp_sent)

If do not need white space at the beginning or end of a line, you can do: 如果一行的开头或结尾不需要空格,则可以执行以下操作:

samp_sent = ' '.join(line.strip() for line in samp_sent)

instead of 代替

samp_sent = ' '.join(samp_sent)
samp_sent = samp_sent.replace("\n", " ")

another alternative: 另一种选择:

print("Input Your Sentence(s) Below (and Then Hit CTRL+D):")
samp_sent = ' '.join(sys.stdin.read().splitlines())
print(samp_sent)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM