Pulpcode

捕获,搅碎,拼接,吞咽

0%

python中的跨行字符串

之前编程写到跨行字符串的时候,在c#中,总是使用+字符拼接。

1
2
3
4
5
string s = "The path of the righteous man is beset on all sides by the inequities of the tyranny of evil man."
+ "blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness,"
+ "for he is truly his brother's keeper and the finder of lost children."
+ "And i will strike down upon thee with great vengeance and furious anger those who attempt to poison and destroy my brothers."
+ "And you will know my name is the lord when i lay my vengeance upon thee.";

后来我使用@符号编写跨行字符串,这样就可以直接编写字符串了。

需要注意的是,在这段由@””包围的字符串中,你的所有格式,都被保留下来了。比如换行符,换行符后面的空格,还是文字前面用于缩进的空白符,都保存在这个字符串中。

1
2
3
4
5
6
string s = @"
The path of the righteous man is beset on all sides by the inequities of the tyranny of evil man.
blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness,
for he is truly his brother's keeper and the finder of lost children.
And i will strike down upon thee with great vengeance and furious anger those who attempt to poison and destroy my brothers.
And you will know my name is the lord when i lay my vengeance upon thee.";

在python中也是这样,只不过需要使用**’’’string’’’**这样3个引号进行包含。

1
2
3
4
5
6
# 缩进的空字符也会保存到字符串中
s = '''The path of the righteous man is beset on all sides by the inequities of the tyranny of evil man.
blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness,
for he is truly his brother's keeper and the finder of lost children.
And i will strike down upon thee with great vengeance and furious anger those who attempt to poison and destroy my brothers.
And you will know my name is the lord when i lay my vengeance upon thee.'''

需要注意的是,在跨行字符串中,就不需要考虑python的缩进控制作用域了。

顺便说一句,这段文字来自《低俗小说》