Python 如何将两个字符串与它们之间的新行连接起来?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27083445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to join two string with a new line between them?
提问by Linda Su
I have two strings like this:
我有两个这样的字符串:
str1 = "my fav fruit apple"
str2 = "my fav vegetable carrot"
I want to join the two strings to become :
我想加入两个字符串成为:
"my fav fruit apple
my fav vegetable carrot"
i.e.: become one string with a new line between them. How to do that?
即:成为一个字符串,它们之间有一个新行。怎么做?
回答by BrenBarn
The simplest way:
最简单的方法:
new_string = str1 + "\n" + str2
回答by Michael Laszlo
You can use the concatenation operator, +:
您可以使用连接运算符+:
str3 = str1 + '\n' + str2
Or you can use the joinmethod on your delimiter, '\n':
或者您可以join在分隔符上使用该方法'\n':
str3 = '\n'.join([str1, str2])
The latter approach works well when you have a bunch of strings in an array.
当数组中有一堆字符串时,后一种方法效果很好。
lines = ['A Story', 'by Me', '', 'An aardvark escaped from the zoo.', '', 'The End']
story = '\n'.join(lines)
print(story)

