How to write multiple strings in one line?

后端 未结 11 605
谎友^
谎友^ 2020-12-01 03:28

I\'ve started to learn Python with LPTHW and I\'ve gotten to exercise 16:

http://learnpythonthehardway.org/book/ex16.html

And feel like an idiot because I ca

相关标签:
11条回答
  • 2020-12-01 03:36

    Here's one way:

    target.write(line1 + '\n' + line2 + '\n' + line3 + '\n')
    

    The reason the following doesn't work

    target.write(line1 \n, line2 \n, line3 \n)
    

    Is that line1 is a variable (note it's not quoted) but '\n' is a string literal (since it's in quotes). The addition operator is overloaded for strings to concatenate (combine) them.

    The reason this doesn't work:

    target.write('line1 \n, line2 \n, line3 \n')
    

    Is because line1 is a variable. When you put it in quotes, it's no longer treated as a variable.

    0 讨论(0)
  • 2020-12-01 03:38

    The author suggested using the formats, the strings and the escapes, so the following works. This implements Python's f-strings:

    target.write(f"{line1} \n{line2} \n{line3} \n")
    
    0 讨论(0)
  • 2020-12-01 03:42

    Your last try looks promising. It should look like:

    "%s \n %s \n %s" % (line1, line2, line3)
    

    this applies the operator % to a string (with 3 %s placeholders) and a tuple of values to substitute (here, strings). The result is the formatted string.

    So you'd need to wrap that in the function which takes the result:

    target.write("%s \n %s \n %s" % (line1, line2, line3) )
    
    0 讨论(0)
  • 2020-12-01 03:43

    This info was really helpful. I got the right results by doing the following:

    target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
    

    The idea of concatenating would never have occurred to me.

    0 讨论(0)
  • 2020-12-01 03:47

    below line works for me,

     target.write(line1 + line + line2 + line + line3 + line)
    

    Before that i added

     line = '\n'
    

    my code like:

     from sys import argv
     script, filename = argv
     print 'Appending process starts on: %r' % filename
     target = open(filename, 'a')
     print 'Enter the contents:\t'
     line1 = raw_input('Next:\t')
     line2 = raw_input('Next:\t')
     line3 = raw_input('Next:\t')
     line = '\n'
     target.write(line1 + line + line2 + line + line3 + line)
     print 'Thank you !'
    
    0 讨论(0)
  • 2020-12-01 03:53

    This worked for me.

    target.write("line1\nline2\nline3\n")

    Also, the keyword which made it clicked for me was mentioned by Ewart, "'\n' only make sense inside a string literal."

    0 讨论(0)
提交回复
热议问题