python - 如何将从.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
,当我尝试打印“密码”值时,它在输出中打印为空行。我需要将其提及为“无”。我怎样才能做到这一点?
解决方案
您可以做的是在解析时检查密码的长度。如果长度<1,只需将其赋值为None。
psd = ''
psd = psd.strip()
if len(psd)<1:
psd= 'None' # you can also just use None without any quotes
print(psd)
推荐阅读
- r - kable full_width 样式选项在表格标题下方打印奇怪的字符
- amazon-web-services - 如何在不修改 Cloudfront 的情况下在 AWS 中设置维护页面?
- java - Spring看不到css文件
- c++ - 验证数组 C++ 中的输入数据
- sql - 如果表 a 是表 b 的子集,在 impala 中找出的最佳方法是什么?
- bash - 为什么我们使用当前目录符号执行 .sh 脚本?
- javascript - 为什么 max-height 在 Chrome 中有效,但在 IE 11 中无效?
- html - 扩展导航栏后CSS对齐
- ios - 由于 iTunes Store 连接错误,Receipt Refresh 导致 Apple Review 拒绝 App
- r - 优化 Shiny Dashboard 情节重绘