簡體   English   中英

Python - 印刷 Output 出現在不同的行上

[英]Python - Printed Output Goes On Different Lines

當我嘗試 output 我的代碼時,它會出現一些隨機行,最后一行很好。 我是初學者。 20分鍾前才開始。

f = open('gamelist.txt')

text = f.readlines()
for line in text:
    print('<div><a href="genericweb'+line+'.html">'+line+'</a></div>')

這是我的 OUTPUT

<div>
  <a
    href="genericwebabc
  .html"
    >abc
  </a>
</div>
<div>
  <a
    href="genericwebdef
  .html"
    >def
  </a>
</div>
<div><a href="genericwebghi.html">ghi</a></div>

如您所見,前兩個不起作用,但最后一個起作用。 文本文件是:“abc def ghi”。 順便說一句,每組字母之間的新行。 任何幫助表示贊賞

你可以使用:

print('<div><a href="genericweb'+line+'.html">'+line+'</a></div>', end=' ')

或嘗試使用它來擺脫換行符:

for line in text:
    line = line.rstrip('\n')
    print('<div><a href="genericweb'+line+'.html">'+line+'</a></div>')

希望能幫助到你

您可以將end關鍵字參數設置為空字符串,它不會打印任何結尾(換行符)。 此參數默認為“\n”,換行符的轉義。 將其設置為空白將導致不打印此換行符。 您還可以將其設置為任何其他字符串以寫入不同的結尾。

print("hello", end="")

您可能應該查看python中 HTML 模板的 Jinja2。

暫無
暫無

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

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