📜  Python|空字符串到无的转换

📅  最后修改于: 2022-05-13 01:55:01.950000             🧑  作者: Mango

Python|空字符串到无的转换

有时,在使用机器学习时,我们可能会遇到空字符串,我们希望将其转换为 None 以保持数据一致性。这个和许多其他实用程序可能需要解决此问题。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用 lambda
可以使用 lambda函数执行此任务。在此,我们使用 or运算符检查字符串是否为 None 或空字符串,并将空字符串替换为 None。

# Python3 code to demonstrate working of
# Empty String to None Conversion
# Using lambda
  
# initializing list of strings
test_list = ["Geeks", '', "CS", '', '']
  
# printing original list 
print("The original list is : " + str(test_list))
  
# using lambda
# Empty String to None Conversion
conv = lambda i : i or None
res = [conv(i) for i in test_list]
  
# printing result 
print("The list after conversion of Empty Strings : " + str(res))
输出 :
The original list is : ['Geeks', '', 'CS', '', '']
The list after conversion of Empty Strings : ['Geeks', None, 'CS', None, None]

方法 #2:使用str()
简单地 str函数可用于执行此特定任务,因为 None 也评估为“False”值,因此不会被选择,而是返回一个转换为 false 的字符串,其评估为空字符串。

# Python3 code to demonstrate working of
# Empty String to None Conversion
# Using str()
  
# initializing list of strings
test_list = ["Geeks", '', "CS", '', '']
  
# printing original list 
print("The original list is : " + str(test_list))
  
# using str()
# Empty String to None Conversion
res = [str(i or None) for i in test_list]
  
# printing result 
print("The list after conversion of Empty Strings : " + str(res))
输出 :
The original list is : ['Geeks', '', 'CS', '', '']
The list after conversion of Empty Strings : ['Geeks', None, 'CS', None, None]