我正在尝试将此 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/