簡體   English   中英

Python,換行有問題

[英]Python, having troubles with new line

我已經編寫了這段代碼來在我完成在一行中提供輸入后打印出一個新行..所以像這樣

netM = ''

while True:
    line = raw_input()
    if not line: break

    netM += ''  + line
    netMs = netM.replace('.', '')
print("\n" + netMs + " = " + netMs + " or " + netM + "\n")

假設我進入,

Pause.now

它會輸出..

Pausenow = Pausenow or Pause.now

但我想一次做很多行,所以它會這樣做..

Pausenow = Pausenow or Pause.now
Pausenow1 = Pausenow1 or Pause.now1
Pausenow2 = Pausenow2 or Pause.now2

如果我進去了

Pause.now
Pause.now1
Pause.now2

等等。

而是這樣做。

pauseNowpauseNow1pauseNow2 = pauseNowpauseNow1pauseNow2 or pause.Nowpause.Now1pause.Now2

您需要為循環的每次迭代打印該行,否則它將繼續將新行附加到前一個,只需將您的打印語句移動到 while 循環中也為您想要的結果不要在netM變量中附加行

netM = ''

while True:
    line = raw_input()
    if not line: break

    netM = ''  + line
    netMs = netM.replace('.', '')
    print(netMs + " = " + netMs + " or " + netM + "\n")

發生這種情況是因為 raw_input() 將輸入作為單個字符串。

您還為每個輸入的輸入將輸入的行添加到 newM 變量。它應該在 for 循環內。 定義一些其他斷點而不是默認的“換行”。

在這里,我將斷點用作“”,即空字符串。 現在,當您輸入空字符串時,此循環將中斷。

breakpoint = ""
while True:
    line = raw_input()
    if line.strip() == breakpoint:
        break
    netM = line
    netMs = netM.replace('.', '')
    print("\n" + netMs + " = " + netMs + " or " + netM + "\n")

在我看來,您應該將單個字符串添加到主字符串 (netM) 中除以'\\n'並打印整個主字符串,一旦 while 循環中斷。

netM = ''

while True:
    line = raw_input()
    if not line:
            break

    netMs = line.replace('.', '')
    netM += netMs + ' = ' + netMs + ' or ' + line + '\n'

print netM

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM