如何将两个字符串与它们之间的新行连接起来? [英] How to join two string with a new line between them?
本文介绍了如何将两个字符串与它们之间的新行连接起来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个这样的字符串:
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?
推荐答案
可以使用连接运算符,+
:
You can use the concatenation operator, +
:
str3 = str1 + '\n' + str2
或者你可以在你的分隔符上使用 join
方法,'\n'
:
Or you can use the join
method on your delimiter, '\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)
这篇关于如何将两个字符串与它们之间的新行连接起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文