[英]Supporting sys.stdin.readlines() as well as command line arguments in python?
[英]Python 3.x: ' '.join() on sys.stdin.readlines() Input Does Not Return Final String When Final Character Is Not a Line/Carriage Break
我想转换成文本块,无论是单行或多行,到一个单一的字符串一个剩余空格" "
结尾。
这是我的代码:
# 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)
如果最后一个字符不是换行符,则它会省略字符串并仅添加" "
。
"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."
→ "Here is one line. "
"Here is one line."
→ " "
无论我输入示例(1),(2)还是(3)作为输入,如何确保最后一行始终出现在print(samp_sent)
?
如果一行的开头或结尾不需要空格,则可以执行以下操作:
samp_sent = ' '.join(line.strip() for line in samp_sent)
代替
samp_sent = ' '.join(samp_sent)
samp_sent = samp_sent.replace("\n", " ")
另一种选择:
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.