![](/img/trans.png)
[英]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.