简体   繁体   中英

python string concatenation split over two lines

for don in open('list.txt', 'r'):
    myURL=don 
    myURL=myURL.replace("rep.php","")
    print(myURL+"test.php")

It's printing

http://www.blabla.com
blablabla.html

When you iterate over a file handle, you get one line at a time with any trailing newline characters . So, the line is probably 'http://www.blabla.com\n' . That's why, when you append 'blabla.html' , the result is split over two lines.

An easy fix is to do

print(myURL.rstrip() + 'blabla.html')

On a side note, it's good practice to manage resources like file handles with context blocks so that the file handle is explicitly closed (and not left to the garbage collector):

with open('list.txt', 'r') as f:
    for don in f:
        ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM