2015-04-01 68 views
3

的我有一个使用pformat()的字典转换为字符串的函数(无关:字符串将与write().py文件后插入)。压痕pformat()输出

所以MY_DCT = {1: 11, 2: 22, 3: 33}将成为一个字符串,像这样:

MY_DCT = { 
    1: 11, 
    2: 22, 
    3: 33} 

有对功能2个要求:必须显示

  1. 快译通项目的第一行之后。
  2. 元素必须缩进4个空格。

下面是函数:

import pprint  

def f(obj_name, obj_body_as_dct): 

    body = '{\n' + pprint.pformat(obj_body_as_dct, indent=4, width=1)[1:] 
    name_and_equal_sign = obj_name + ' = ' 

    return name_and_equal_sign + body + '\n\n' 


d = {1: 11, 2: 22, 3: 33} 

print(f('MY_DCT', d)) 

如果indent=0我得到这个字符串:

MY_DCT = { 
1: 11, 
2: 22, 
3: 33} 

如果indent=4我得到这个字符串:

MY_DCT = { 
    1: 11, 
    2: 22, 
    3: 33} 

我查了parameterspformat()但我无法弄清楚如何使正确数量的空格出现在每一行上。

我知道我可以使用replace(),+' '等修复字符串,但即时通讯想知道额外的空白来自哪里,如果我可以摆脱它通过正确设置参数(如果这甚至可能,那是)。

注意:如果有更好的方法来实现上述,请让我知道。

回答

0

indentpformat的默认值是1,这样键出现一个在另一个之下。

例如,pformat(d, indent=0, width=1)将导致该字符串:

{1: 11, 
2: 22, 
3: 33} 

indent=1

{1: 11, 
2: 22, 
3: 33} 

indent=2

{ 1: 11, 
    2: 22, 
    3: 33} 

少了一个在第一行总是空格。


由于目标是显示第一行之后的dict元件,并且具有由4个空格缩进的所有元素时,第一元件之前加入一个单一的空白,并使用indent=4将某些类型的字典工作(由@所建议的逻辑)。

但是像d = {1: {'a': 1, 'b': 2}, 2: 22, 3: 33}类型的字典会显得比较难看,因为indent会影响深度大于1类型的字典的外观以及:

MY_DCT = { 
    1: { 'a': 1, 
      'b': 2}, 
    # ^
    # | 
    # ugly 
    2: 22, 
    3: 33} 

最有吸引力的解决方案(对于数据IM工作)保持indent=1并为第一个元素添加3个空格,其余为4个空格。

def f(obj_name, given_dct): 
    """ 
    Converts given dct (body) to a pretty formatted string. 
    Resulting string used for file writing. 

    Args: 
     obj_name: (str) name of the dict 
    Returns: 
     (str) 
    """ 

    string = pp.pformat(given_dct, width=1)[1:] 

    new_str = '' 
    for num, line in enumerate(string.split('\n')): 
     if num == 0: 
      # (pprint module always inserts one less whitespace for first line) 
      # (indent=1 is default, giving everything one extra whitespace) 
      new_str += ' '*4 + line + '\n' 
     else: 
      new_str += ' '*3 + line + '\n' 

    return obj_name + ' = {\n' + new_str 


s = f(obj_name='MY_DCT', given_dct=d) 

在此字符串所得:

MY_DCT = { 
    1: {'a': 'aa', 
     'b': [1, 
       2, 
       3]}, 
    2: 22, 
    3: 33} 
1

参数不是您的打印问题。添加换行符('\n')时会出现问题。正如你从这个例子可以看到:

import pprint  

def f(obj_name, obj_body_as_dct): 

    body = '{' + pprint.pformat(obj_body_as_dct, indent=4, width=1, depth=1)[1:] 
    name_and_equal_sign = obj_name + ' = ' + '\n' 

    return '"""' + name_and_equal_sign + body + '"""' + '\n\n' 


d = {1: 11, 2: 22, 3: 33} 

print(f('MY_DCT', d)) 

此输出:

"""MY_DCT = 
{ 1: 11, 
    2: 22, 
    3: 33}""" 

的换行符和印刷的第一行中的另外的一个“{”就是为什么只有第一排的产量似乎被一个小空间所抵消。

UPDATE#1

位具有这些值修补后,我能够以匹配所需的输出:

import pprint  

def f(obj_name, obj_body_as_dct): 

    body = pprint.pformat(obj_body_as_dct, indent=4, width=1, depth=1)[1:] 
    name_and_equal_sign = obj_name 

    return '"""' + name_and_equal_sign + ' = ' + '{' + '\n ' + body +'"""' + '\n\n' 
                 #^I added a space in this newline 

d = {1: 11, 2: 22, 3: 33} 

print(f('MY_DCT', d)) 

上面的代码输出:

"""MY_DCT = { 
    1: 11, 
    2: 22, 
    3: 33}""" 

所以,实质上,你只需要一个换行符(用代码显示)中的一个空格。

更新#2

继在评论你的建议:

试试这个:print(pp.pformat({1:11, 2:22, 3:33}, indent=0, width=1)), 与缩进从0到2,你会发现,它适用于少了一个 第一行的空格。这是建立pformat()的方式。 - @用户5061

我尝试这样做:

import pprint as pp 

for i in range(0,3): 
    print(pp.pformat({1:11, 2:22, 3:33}, indent=i, width=1)) 

它给了我这样的输出:

{1: 11,  #Indent = 0 Each entry (except 1) is indented by 0 spaces, because the "{" operator is in the way. 
2: 22, 
3: 33} 
{1: 11,  #Indent = 1 Each entry is indented by 1 spaces 
2: 22, 
3: 33} 
{ 1: 11, #Indent = 2 Each entry is indented by 2 spaces 
    2: 22, 
    3: 33} 

正如你所看到的,这个问题仍是这个: “{
如果那不是,那么缩进甚至会在整个过程中。编码功能pformat()以调整该字符。

+0

试试:'打印(pp.pformat({1:11,2:22,3:33},缩进= 0,宽度= 1) )','indent'从0变为2.你会注意到,它在第一行应用了少一个空格。这是'pformat()'的构建方式。 – 2015-04-01 19:43:17

+0

@ user5061您是否尝试过使用我的Python代码?我能够用一个空间解决你的问题。 – logic 2015-04-01 20:39:46

0

Logic's answer你有覆盖,为什么你有缩进问题。由于(IMO)更简洁的方法,但是,您可以使用json。该输出被假定由元件你的意思字典元素:

import json 
obj_name = 'MY_DCT = ' 
obj_body_as_dct = {1: 11, 2: 22, 3: 33} 

stringy = "\"\"\"" + obj_name + "{" \ 
      + str(json.dumps(obj_body_as_dct, indent=4, separators=(',', ': ')))[1:] + "\"\"\"" 
print(stringy) 

输出:

"""MY_DCT = { 
    "1": 11, 
    "2": 22, 
    "3": 33 
}""" 
+0

该字符串将被插入到一个'.py'文件中。这个输出将是无效的语法。 – 2015-04-01 19:07:57

+0

@ user5061您希望的输出*精确*,如您的第一个显示器所示?我可以编辑,如果是这样,并放置在一个字符串。 – miradulo 2015-04-01 19:09:08

+0

您的输出与我在我的问题中的输出不同。如果您复制该输出并将其插入py文件中,则会出现语法错误。 – 2015-04-01 19:16:05