簡體   English   中英

當從行讀取時返回換行符 - Python

[英]When reading from line returns newline - Python

我正在嘗試編寫一個python腳本,通過從文件中讀取來生成一些代碼。 但是它沒有按預期工作。

碼:

with open('continent.txt') as fp:
    for line in fp:
        print "text ", line ," here"

結果

$ python ContinentCode.py

text  North America
here
text  South America
here
text  Central America

期望

text  North America here
text  South America here
text  Central America here

調用.strip()上方法line

with open('continent.txt') as fp:
    for line in fp:
        print "text ", line.strip('\r\n') ," here"

請注意strip的參數指定要刪除的字符。 默認情況下.strip()刪除空格和制表符......不確定這是否是您想要的。

嘗試:

print "text ", line.strip() ," here"

關於帶更多信息點擊這里

你的問題似乎與這里提出的問題相同。

總結上面的線程,你可以使用print "text ", line.rstrip("\\n"), " here" line.rstrip(“\\ n”)將返回刪除字符串line包含的任何“\\ n”。

或者你可以for line in fp.splitlines()使用for line in fp.splitlines() .splitlines()返回沒有換行符的行列表。 就個人而言,我是分裂線的粉絲。 如果你願意,你可以做一些像lines = fp.splitlines() for line in lines: [code goes here]

暫無
暫無

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

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