📜  Python|将 None 转换为空字符串

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

Python|将 None 转换为空字符串

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

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

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

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

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