Python如何拆行长单行字符串且不插入多余空格或换行?
Python 拆分单行超长字符串的最优方案
你遇到的问题是在代码中拆分单行长字符串时,容易引入多余缩进空格,现有方案你觉得可维护性不高,下面给出两种不同场景下的简便方案:
方案1:编译期隐式拼接(推荐,性能最高)
你提到的括号包裹多个字符串字面量的写法其实是Python官方推荐的标准方案,它的拼接逻辑在编译阶段就完成,运行时没有任何额外开销,可维护性差的问题只需要调整写法习惯就能规避:
- 统一将空格放在每一行字符串的末尾,调整后的写法如下:
long_string = ( "This is a very long string. " "Since it is a one-line string, I really want " "to keep it without any new line. However, I don't like how " "it looks in my code and it is annoying me" )
这种写法后续增删字符串行只需要对应维护当前行末尾的空格即可,非常直观,也不需要额外导入依赖。
方案2:文档字符串清理(适合超长字符串,写起来最省事)
如果字符串长度非常长,不想每一行都加引号,可以用标准库的inspect.cleandoc自动清理公共缩进,再替换换行符为空格即可:
import inspect long_string = inspect.cleandoc(""" This is a very long string. Since it is a one-line string, I really want to keep it without any new line. However, I don't like how it looks in my code and it is annoying me """).replace('\n', ' ')
cleandoc会自动去掉所有行前的公共缩进,再把换行符替换为单个空格,就能得到没有多余字符的单行字符串,写的时候不需要额外处理每行的引号,改起来更方便。
不推荐的写法
你之前用的反斜杠换行的写法,只要删掉第二行开始的缩进就能避免多余空格,但这种写法容错性极低,反斜杠后不能有任何空格、注释,非常容易出BUG,Python社区普遍不推荐使用:
# 可以运行但不推荐 long_string = "This is a very long string. Since it is a one-line string, I really want \ to keep it without any new line. However, I don't like how it looks in my \ code and it is annoying me"
内容的提问来源于stack exchange,提问作者Pagly
相关产品推荐
相关产品推荐

