jstacks
jstacks

Reputation: 2437

How to write multiple strings in one line?

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 can't figure out one of the seemingly simple "extra credit" assignments that wants the following:

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

To be condensed to one line of code. I've tried some of the following:

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

Or:

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

Or:

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

I just can't get it to rewrite the line1, line2, and line3 strings all in the same line. And I've tried various other combinations with and without commas, quotes, etc. I keep getting varying errors, like Invalid Syntax or that I have too many arguments.

Upvotes: 19

Views: 82979

Answers (12)

Mohit Gaikwad
Mohit Gaikwad

Reputation: 340

This is simple:

with open('file.txt','w') as file:

    file.write('a: {}, b: {}  '.format(a,b))

Upvotes: 0

Tash
Tash

Reputation: 31

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."

Upvotes: 0

ManoloDr95
ManoloDr95

Reputation: 1

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

If you want it on the same line, the above will work, if you want it on separate lines add the "\n" for new line.

Upvotes: 0

Dave1701
Dave1701

Reputation: 1

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.

Upvotes: 0

Murphy Kuffour
Murphy Kuffour

Reputation: 21

LPTHW: Exercise 16, Study Drill 3

There's too much repetition in this file.

Use strings, formats, and escapes to print out line1, line2, and line3 with just one target.write() command instead of six.

more powerful implementation of target.write # Study Drill 3

formatter = "{0}\n{1}\n{2}\n"
target.write(formatter.format(line1,line2,line3))

Upvotes: 0

Captain Price
Captain Price

Reputation: 11

Not sure if this is pythonic way, but it gets the job done anyway.

a = f"""
{line1}
{line2}
{line3}
"""
target.write(a)

Upvotes: 0

22ManyPies
22ManyPies

Reputation: 11

Don't try to overcomplicate it. The string works the same as when you print something, except you are starting with target.write instead so you can write it to the file instead of printing.

For example, if you were going to print the variables and put them on a new line each you would use this string

print(f"{line1} \n{line2} \n{line3} \n")

In exercise 5, you learnt that to pull in a variable you need to put {} around the name you gave to the variable and if you want to pull variables into a string, you must start your string with f" In exercise 9, you learnt to use \n if you want to put something on a new line

Now you want to write to the file instead of printing it so the string is the same except it starts with target.write this time target.write(f"{line1} \n{line2} \n{line3} \n")

Upvotes: 0

Irina
Irina

Reputation: 45

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")

Upvotes: 2

Ranjithkumar T
Ranjithkumar T

Reputation: 1956

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 !'

Upvotes: 2

Winston Ewert
Winston Ewert

Reputation: 45039

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

'\n' only make sense inside a string literal. Without the quotes, you don't have string literals.

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

Ok, now everything is a string literal. But you want line1, line2, line3 to not be string literals. You need those as python expressions to refer the variables in question. Basically, you have to put quotes around strings that are actually text like "\n" but not around variables. If you did that, you might have gotten something like:

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

What is 2 2? It's nothing. You have to specify to python how to combine the two pieces. So you can have 2 + 2 or 2 * 2 but 2 2 doesn't make any sense. In this case, we use add to combine two strings

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

Moving on,

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

Again \n only makes sense inside a string literal. The % operator when used to produce strings takes a string as its left side. So you need all of that formatting detail inside a string.

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

But that produce 3 string literals, you only want one. If you did this, write complained because it excepts one string, not 3. So you might have tried something like:

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

But you want to write the line1, line2, line3 to the file. In this case, you are trying to the formatting after the write has already finished. When python executes this it will run the target.write first leaving:

None % (line1, line2, line3)

Which will do nothing useful. To fix that we need to to put the % () inside the .write()

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

Upvotes: 51

David Ly
David Ly

Reputation: 31586

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.

Upvotes: 4

Kos
Kos

Reputation: 72231

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) )

Upvotes: 7

Related Questions