简体   繁体   English

在python中写入文本文件时如何在单词之间留一个空格

[英]How do I make a space between words when writing to a 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 the text file the name and score do not have space between them for example, how could I change "James14" in to "James 14"但是,在文本文件中,名称和分数之间没有空格,例如,我如何将“James14”更改为“James 14”

You can 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]))

You'll have to write that 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 used from __future__ import print_function , you could also use the print() function , and have it add the space for you:如果您使用的是 Python 3,或者使用from __future__ import print_function ,您也可以使用print()函数,并让它为您添加空间:

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

I set end to an empty string, because otherwise you'll also get a newline character.我将end设置为一个空字符串,否则你也会得到一个换行符。 Of course, you may actually want that newline character, if you are writing multiple names and scores to the file and each entry needs to be on its own line.当然,如果您将多个名称和分数写入文件并且每个条目都需要在自己的行上,您可能实际上需要换行符。

A simple way would be to simply concatenate with a space character一种简单的方法是简单地与空格字符连接

f.write(name + ' ' + score)

A more robust method (for if the formatting gets more involved) is to use the format method一种更健壮的方法(如果格式涉及更多)是使用format方法

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

Bhargav and Martjin's answers are good. Bhargav 和 Martjin 的回答很好。 There are many ways to do it.有很多方法可以做到这一点。 I'd like to add that the .format way seems to be a little better because you can potentially reuse the arguments and organize your code better.我想补充一点, .format方式似乎更好一些,因为您可以重用参数并更好地组织代码。

You should format a string.您应该格式化一个字符串。

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

Basically, %(Name)s is a placeholder (denoted by the %) for a string (denoted by the s following the parentheses), which we will reference by "Name".基本上,%(Name)s 是一个字符串(由括号后面的 s 表示)的占位符(用 % 表示),我们将通过“Name”引用它。 Following our format string, which is wrapped in "", we have this weird thing:在我们用“”包裹的格式字符串之后,我们有一个奇怪的东西:

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

This is a dictionary that provides replacements for the "Name" and "Score" placeholders.这是一个提供“名称”和“分数”占位符替换的字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM