【问题标题】:Linebreak a raw string换行原始字符串
【发布时间】:2019-11-02 03:44:31
【问题描述】:

我正在寻找一种在 python 中换行长原始字符串的好方法。 这样做的原因是,我经常将 windows 路径与pathlibs Path 一起使用,因为这样我可以方便地在 windows 和 *nix 上进行复制粘贴,如下所示:

from pathlib import Path
my_long_path = Path(r'C:some\very\long\path')

现在,文件路径自然会变得很长,为了更好地格式化代码,我有时想对原始字符串进行换行。

由于换行符号,三重引号不起作用:

a = r'''some\
very\long\path'''

--> 'some\\\nvery\long\path'

所以我知道的唯一选择是:

a = r'some\'\
r'very\long\path'

它可以工作,但感觉有点不像 Python。有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python code-formatting rawstring


    【解决方案1】:

    您可以使用括号: 这也可以在这里找到How to write very long string that conforms with PEP8 and prevent E501

    s = ("this is my really, really, really, really, really, really, " # comments ok
         "really long string that I'd like to shorten.")
    
    print(s)
    >>>> this is my really, really, really, really, really, really, really long string that I'd like to shorten.                                                                            
    

    【讨论】:

    • 但这不再是原始字符串了,不是吗?
    • 是的,它是一个原始字符串
    猜你喜欢
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 2013-01-19
    • 2018-04-26
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多