文章目录三引号字符串会原样保留换行和空格 是空字符串三引号会保留换行。如果不想要开头的换行可以这样写 \ 后面的反斜杠可以去掉三引号后的第一个换行.或者紧跟内容如果不像要结尾的换行可以结尾的三引号紧跟内容结尾有换行是因为结尾打了回车三引号会保留缩进空格想让内容顶格有三种常见写法写法一内容真的顶格写.但是在函数里面这样写不太好看写法二用 textwrap.dedent() 去掉公共缩进写法三用 .strip() 去掉首尾空行。.strip() 只去掉首尾空白不会去掉每一行前面的缩进总结 推荐用textwrap去掉公共缩进用strip去掉首尾空行、首尾空格三引号字符串会原样保留换行和空格“”“”“” 是空字符串sprint(s)print(repr(s))# 输出 三引号会保留换行。开头3引号不紧跟内容会多一个换行。内容结束回车后在写3引号也会多一个换行。s hello world print(s)print(***************)print(repr(s))如果不想要开头的换行可以这样写“” \ 后面的反斜杠可以去掉三引号后的第一个换行.或者紧跟内容shello world print(repr(s))# 结果 hello world ******* hello\nworld\n 或者这样s\ hello world print(s)print(*******)print(repr(s))# 结果 hello world ******* hello\nworld\n 如果不像要结尾的换行可以结尾的三引号紧跟内容s hello worldprint(s)print(*******)print(repr(s))# 结果 hello world ******* \nhello\nworld 结尾有换行是因为结尾打了回车第一个\n是jkl这一行结束第一个\n是空白行结束s abc def print(s)print(****)print(repr(s))print(----------------------)ss ghi jkl print(ss)print()print(repr(ss))三引号会保留缩进空格defdemo():s hello world print(s)print(*****)print(repr(s))demo()# 结果: hello world ***** \n hello\n world\n 想让内容顶格有三种常见写法写法一内容真的顶格写.但是在函数里面这样写不太好看shello worldprint(s)print(********)print(repr(s))函数里面这么写不好看defdemo():shello worldprint(s)print(*****)print(repr(s))demo()写法二用 textwrap.dedent() 去掉公共缩进importtextwrapdefdemo():stextwrap.dedent( hello(缩进8个) world(缩进8个) ni(缩进12个) hao(缩进8个) ya(缩进16个) )print(s)print(******)print(repr(s))demo()写法三用 .strip() 去掉首尾空行。.strip() 只去掉首尾空白不会去掉每一行前面的缩进s hello world .strip()print(s)print(******)print(repr(s)).strip() 只去掉首尾空白不会去掉每一行前面的缩进s hello world .strip()print(s)print(******)print(repr(s))总结 推荐用textwrap去掉公共缩进用strip去掉首尾空行、首尾空格importtextwrapdefdemo():stextwrap.dedent( hello(缩进8个) world(缩进8个) ni(缩进12个) hao(缩进8个) ya(缩进16个) ).strip()print(s)print(******)print(repr(s))demo()