當(dāng)input輸入內(nèi)容的時候,許多情況下輸入回車鍵另起一行輸入,但是這時候Pycharm就執(zhí)行程序,然后結(jié)束,導(dǎo)致無法繼續(xù)輸入內(nèi)容。
原因:Python默認(rèn)遇到回車的時候,輸入結(jié)束。所以我們需要更改這個提示符,在遇到其他字符的時候,輸入才結(jié)束。
比如有一個任務(wù):
請輸入文件名:憫農(nóng).txt
請輸入內(nèi)容【單獨(dú)輸入‘:q‘保存退出】:
鋤禾日當(dāng)午,汗滴禾下土。
誰知盤中餐,粒粒皆辛苦。
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# -*- coding: utf-8 -*- file_name = input ( "請輸入文件名:" ) file_name = file_name + ".txt" something_file = open (file_name, "w" ) stopword = ":q" file_content = "" print ( "請輸入內(nèi)容【單獨(dú)輸入‘:q‘保存退出】:" ) for line in iter ( input ,stopword): file_content = file_content + line + "\n" print (file_content, file = something_file) something_file.close() |
或者:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# -*- coding: utf-8 -*- def file_write(file_name): f = open (file_name, 'w' ) print ( '請輸入內(nèi)容【單獨(dú)輸入\':q\'保存退出】:' ) while True : file_content = input () if file_content ! = ':q' : f.write( '%s\n' % file_content) else : break f.close() file_name = input ( '請輸入文件名:' ) file_write(file_name) |
以上這篇python將回車作為輸入內(nèi)容的實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/chaowanghn/article/details/53964473