0

I just had a quick question that keeps breaking my program. For some reason file.write() will only take in 1 string or variable and my question is there any way around this?

For example Im asking if it is possible to write multiple variables or strings to a file at once. Like this but without .write() because it doesn't allow you to.

file.write("apples: ", numApples, "\n oranges: ", numOranges)

Any help or suggestions are welcome!

The best answer I thought of right now is to make it all a string then send it to the file.

1
  • 2
    file.write("apples: " + str(numApples) + "\n oranges: " + str(numOranges)) Commented Sep 27, 2014 at 18:31

4 Answers 4

3

You can convert all the arguments to string and append them together.

For example, str(var) will convert var to string type.

You can simply use str(numApples) and so on in your case and append them using + (string concatenate) operator. The modified code will look like

file.write("apples: " + str(numApples) + "\n oranges: " + str(numOranges))

Here you have just one string argument instead of 4.

Sign up to request clarification or add additional context in comments.

2 Comments

Its the same thing I just showed DOOM I would have to do it before the .write then send the new string there but I was wondering if there was an easier way.... Nevermind Im an idiot
Yeah I still had the "," in there instead of the "+". Like I said stupid mistake
2

you could also use format - :

file.write("apples: {0}\n oranges: {1}".format(numApples, numOranges) )

This gives you the flexibility to add formatting to the numbers, which you don't have with the the simple string concatenation solution.

2 Comments

What do you mean by that? Im still new to python so Im a little confused.
For example, you can do things like file.write("apples:{0:5d}\noranges:{1:4d}".format(numApples, numOranges)) to line the numbers up.
0

Use file.writelines, which takes an iterable of strings, rather than a single string.

Or else use print(*args, file=) which takes anything and calls str() for you.

Comments

0

You need to make one arguemnt from your strings, there are few ways to do that:

  1. make each part a string using str(), then concatenate using a '+'
  2. Using str.format
  3. Using nice and concise old syntax:

    file.write("apples: %s\noranges:%s" % (numApples, numOranges))
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.