How to make space between words when writing to text file in python

The following code writes to a text file

if classno== '1':
    f = open("class1.txt", "a")
if classno== '2':
    f = open("class2.txt", "a")
if classno== '3':
    f = open("class3.txt", "a")
f.write(name) 
f.write(score)
f.close()

      

However, in a text file, the name and the score do not have a place in between, for example how can I change "James14" to "James 14"

+3


source to share


5 answers


You may try

f.write(name) 
f.write(' ') 
f.write(score)

      

or

f.write(name + ' ') 
f.write(score)

      

or

f.write(name ) 
f.write(' ' +score)

      



or

f.write("{} {}".format(name,score)) 

      

or

f.write("%s %s"%(name,score)) 

      

or

f.write(" ".join([name,score]))

      

+5


source


You will need to write this space:

f.write(name) 
f.write(' ') 
f.write(score)

      

or use string formatting:

f.write('{} {}'.format(name, score))

      



If you are using Python 3 or are using from __future__ import print_function

, you can also use a function print()

and add its space for you:

print(name, score, file=f, end='')

      

I set end

to empty string because otherwise you will also get a newline character. Of course, you may need this newline character if you are writing multiple names and evaluations to the file and each entry must be on a separate line.

+2


source


A simple way would be to just concatenate with a spatial symbol

f.write(name + ' ' + score)

      

A more reliable method (if the formatting becomes more attractive) is to use the method format

f.write('{} {}'.format(name, score))

      

+1


source


Bhargava and Marjin's answers are good. There are many ways to do this. I would like to add that the way .format

seems to be a bit better because you can reuse the arguments and arrange your code better.

+1


source


You have to format the string.

output = "%(Name)s %(Score)s" %{'Name': name, 'Score':score}
f.write(output)
f.close()

      

Basically,% (Name) s is a placeholder (denoted by%) for the string (denoted by s following the parentheses) that we will refer to as "Name". After our format string, which is wrapped in "", we have this weird thing:

% {'Name': name, 'Score': score}

It is a dictionary that provides replacement for the "Name" and "Score" placeholders.

0


source







All Articles