首页 > 解决方案 > 如何将从.txt文件解析的空字符串转换为None?

问题描述

import os

pwd1 = str()
pwd2 = None
pwd3 = ""
pwd4 = " "

print("1:%s" %pwd1)
print("2:%s" %pwd3)
print("3:%s" %pwd3)
print("4:%s" %pwd4)

Test.txt 文件内容:

[Section1]
username : testuser
password : validpwd

[Section2]
username : testuser
password : validpwd

[Section3]
username : testuser
password : 

[Section4]
username : testuser
password : validpwd

Section3包含password :为空行。

我已经从 解析了“密码”字段的值Section3,当我尝试打印“密码”值时,它在输出中打印为空行。我需要将其提及为“无”。我怎样才能做到这一点?

标签: python

解决方案


您可以做的是在解析时检查密码的长度。如果长度<1,只需将其赋值为None。

psd = ''
psd = psd.strip()
if len(psd)<1:
    psd= 'None' # you can also just use None without any quotes
print(psd)

推荐阅读