Python 3.x Python使用列表理解替换字符串列表中的空字符串
我有一张这样的清单Python 3.x Python使用列表理解替换字符串列表中的空字符串,python-3.x,replace,Python 3.x,Replace,我有一张这样的清单 test1 = ['a', 'b', 'c', '', 'd'] 我希望用hello来代替 test2 = [w.replace('', 'test') for w in test1 ] 输出:['a','b','c','d'] 那么,如何使用列表理解来实现它呢 test1 = ['a', 'b', 'c', '', 'd'] for n in range(len(test1)): if not test1[n]: test1[n] = 'hello' 空字
test1 = ['a', 'b', 'c', '', 'd']
我希望用hello来代替
test2 = [w.replace('', 'test') for w in test1 ]
输出:['a','b','c','d']
那么,如何使用列表理解来实现它呢
test1 = ['a', 'b', 'c', '', 'd']
for n in range(len(test1)):
if not test1[n]:
test1[n] = 'hello'
空字符串有一个假值,您也可以使用test1[n]=以下内容:
x = ['a', 'b', 'c', '', 'd']
['hello' if s=='' else s for s in x]
['a', 'b', 'c', 'hello', 'd']
一份清单是:
[t if t is not '' else 'hello' for t in test1]
欢迎来到SO!我不太明白你在这里试图做什么,我的输出也不符合你的。我认为['testtest'、'testbtest'、'testctest'、'test'、'testdtest']而不是['a'、'b'、'c'、'd']是您的帖子的状态。你能澄清你的意图吗?哦,你说得对,如果我运行test2=[w.replace,test1中w的“test”,输出就像你看到的一样,我希望替换为“test”,你知道怎么做吗