python - 如何在Python 2到3升级中修改 "{:<25}"格式

标签 python python-2.7 python-3.6

我正在尝试将此 python2.7 代码转换为 python3.6

def write_to_zip(x, zf, vocab_start):
    curr_name = "{0}_S{1}_{2}".format(x['study_name'], x['subject_id'], x['repeat_num'])
    vocab_string = x[vocab_start:].to_string(header = False, index = False).replace('\n','').encode("utf-8")
    demo_string = ("{:<25}"*(vocab_start)).format(*x[0:vocab_start].replace(r'', np.nan, regex=True))
    print(demo_string)
    string_to_write = demo_string + vocab_string
    zf.writestr("{}.txt".format(curr_name), string_to_write)

但是我收到 demo_string = ("{:<25}"*(vocab_start)).format(*x[0:vocab_start].replace(r'', np.nan, regex=True)) 的以下错误

('unsupported format string passed to NoneType.__format__', 'occurred at index 0')

x看起来像:

study_name                 English L1
subject_id                          2
repeat_num                          1
completed                        True
last_modified    2019-08-05 06:57 UTC

并生成 demo_string

English L1               2                        1                        1                        2019-08-05 06:57 UTC

vocab_start = 34 在本例中

在Python3中我应该用什么替换{:<25}才能得到相同的结果?

最佳答案

更改在于格式字符串应用于未实现 __format__ 的类型的方式。在您的情况下,您的 x 列表中没有 None 。您可以删除任何 None(或替换它们),或强制将所有参数格式化为字符串。

# Convert `None` values
demo_string = ("{:<25}"*(vocab_start)).format(*('None' if value is None else value for value in x[0:vocab_start].replace(r'', np.nan, regex=True)))

# Force everything to be converted to a string before formatting (with !s)
demo_string = ("{!s:<25}"*(vocab_start)).format(*x[0:vocab_start].replace(r'', np.nan, regex=True))

注意。我不了解 numpy,因此很可能有更好的方法来实现第二个选项。

关于python - 如何在Python 2到3升级中修改 "{:<25}"格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58267818/

相关文章:

python - 在 Matplotlib 极坐标图上设置径向轴

python - 同时插入和扩展列表?

用于搜索专利数据库的 Python 模块,即 USPTO 或 EPO

python - Unicode字符变量导致SyntaxError

Python:为 csv.DictWriter 设置引号?

python sqlalchemy 联合查询 ,'Query' 对象没有属性 'spends'

python - 如何在 Python 2.7 中一次解码一行 unicode?

python - Windows:在 Windows 资源管理器中按下 Ctrl+C 时实际发生了什么

python - 如何修复这些相对导入错误

python - 为 pandas 中的所有列生成列矩阵