简体   繁体   English

用字符串写多行文字

[英]Writing Multiline text in a string

Assume we want to have a string of this form: 假设我们要使用以下形式的字符串:

a b c
d e f
g h i

I don't have access to all lines at one time and I get them one by one in different parts of my code. 我无法一次访问所有行,而是在代码的不同部分中一一对应。 So, I want to have a string and update the string when I have a new line to write there. 因此,我要有一个字符串并在有新行写入时更新该字符串。

I can write each line in a string, but when I use "\\n" to go the next line like this 我可以在字符串中写每一行,但是当我使用“ \\ n”转到下一行时,就像这样

str = "a b c" + "\n" + "d e f" + "\n" + "g h i" 
str

this is the output: 这是输出:

'a b c\nd e f\ng h i'

Any idea for making the output correct? 有什么想法可以使输出正确吗?

If you're just trying to print it, this seems to work for me. 如果您只是尝试打印它,这似乎对我有用。

print("a b c \nd e f \ng h i")

Hope that helps. 希望能有所帮助。

Simple solution is three quotes. 简单的解决方案是用三个引号引起来。

string="""a b c
d e f
g h i"""

print(string)

When you type a variable name in the python shell, it returns the value of that variable. 当您在python shell中键入变量名称时,它将返回该变量的值。 In your case, the value of str does have embedded \\n in it. 在您的情况下, str的值的确嵌入了\\n (As you know from the way you're using it, a string can have any number of newlines in it.) The shell is displaying the raw value of the string. (从使用方式可以知道,字符串中可以包含任意数量的换行符。)外壳程序将显示字符串的原始值。

If you do anything with that string, however, you'll see the newlines behaving as you expect them to. 但是,如果对该字符串执行任何操作,则会看到换行符按预期方式运行。

For example, print(str) outputs the string formatted in the way you expect it to be. 例如, print(str)以您期望的方式输出格式化的字符串。

Similarly, 同样,

with open("myfile.txt", "w") as myfile:
    myfile.write(str)

will produce a file called myfile.txt with the three lines that you want to see in it. 将会生成一个名为myfile.txt的文件,其中包含您要在其中看到的三行内容。

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

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