简体   繁体   中英

Why is a new line being created when concatenating strings

I'm trying to open a file, and edit a specific line. When I concatenate a character onto one of the lines, it works, but inserts a new line. However I don't want a new line. Here is the code:

def moveCurlyInline(line, i):
    with open('test.js', 'r') as inputFile:
        data = inputFile.readlines()
        print(data[0])
        print(data[0] + ' {')

The print outputs:

function hello()

then:

function hello()
 {

I need the curly bracket to be on the same line as the function hello. Any idea what's wrong with my code?

f.readline() reads a line from the file, including the newline at the end of the line.

Try stripping the extra newline:

data = [line.rstrip("\n") for line in inputFile]

您可以通过以下方式删除换行符

inputFile.read().striplines()

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