如何在Python字典中正确格式化长字符串

时间:2017-06-27 21:35:16

标签: python python-3.x dictionary formatting

你可以想象我已经开始使用Python了(对于noob问题感到抱歉)。我正在编写一个使用一些长字典条目的代码,而且我很难让Python满足80个字符的限制。

以下是我的词典片段:

"Hybrid functionals": {
    "B1LYP": "The one - parameter hybrid functional with Becke '88 exchange and Lee - Yang - Parr correlation(25 % HF exchange)",
    "B3LYP and B3LYP/G": "The popular B3LYP functional (20% HF exchange) as defined in the TurboMole program system and the Gaussian program system, respectively",
    "O3LYP": "The Handy hybrid functional",
    "X3LYP": "The Xu and Goddard hybrid functional",
    "B1P": "The one-parameter hybrid version of BP86",
    "B3P": "The three-parameter hybrid version of BP86",
    "B3PW": "The three-parameter hybrid version of PW91",
    "PW1PW": "One-parameter hybrid version of PW91",
    "mPW1PW": "One-parameter hybrid version of mPWPW",
    "mPW1LYP": "One-parameter hybrid version of mPWLYP",
    "PBE0": "One-parameter hybrid version of PBE",
    "PW6B95": "Hybrid functional by Truhlar",
    "BHANDHLYP": "Half-and-half hybrid functional by Becke"},

那么,在字典中处理极长字符串的正确方法是什么?

谢谢你们

2 个答案:

答案 0 :(得分:3)

Python没有" 80个字符限制"。这是一种风格推荐,但你可以自由地不去尊重它。但是,它可能会使您的代码更难阅读,并且您的编辑器可能会警告您这些长线。

解决问题的一种方法是使用automatic string concatenation

  

多个相邻的字符串或字节文字(由空格分隔),   可能使用不同的引用约定,允许和它们的   意思与它们的连接相同。因此,"你好" '世界'是   相当于" helloworld"。

所以,你可以写下你的词典:

{
    "B1LYP": "The one - parameter hybrid functional with Becke '88" 
             " exchange and Lee - Yang - Parr correlation(25 % HF " 
             "exchange)",
    ...

答案 1 :(得分:2)

Python本身并不在乎;你收到警告,而不是错误,因为你没有遵守正确的格式。如果您想要修复它,请尝试按Enter键分割线。

如果您有一个非常大的字典,请考虑将其放入文本文件并在需要时从中读取。