54

I have:

d = [1,'q','3', None, 'temp']

I want to replace None value to 'None' or any string

expected effect:

d = [1,'q','3', 'None', 'temp']

a try replace in string and for loop but I get error:

TypeError: expected a character buffer object
2
  • 2
    If you need to turn None into a string for whatever you're doing next (that expects a character buffer object), why don't you need to turn the 1 into a string as well? Commented Oct 14, 2013 at 15:38
  • 1
    You may want to take a step back and consider how the list is built in the first place. Commented Oct 14, 2013 at 16:12

7 Answers 7

94

Use a simple list comprehension:

['None' if v is None else v for v in d]

Demo:

>>> d = [1,'q','3', None, 'temp']
>>> ['None' if v is None else v for v in d]
[1, 'q', '3', 'None', 'temp']

Note the is None test to match the None singleton.

Sign up to request clarification or add additional context in comments.

3 Comments

Just a note to reader in case it's not obvious that this creates a new list - it doesn't modify the existing list d.
This can be simplified to [v or 'None' for v in d] if you know that you don't have empty strings or anything else that evaluates as False (which may be a risky assumption).
@alphabetasoup: exactly, which is why I don't do that in a generic answer on SO.
17

You can simply use map and convert all items to strings using the str function:

map(str, d)
#['1', 'q', '3', 'None', 'temp']

If you only want to convert the None values, you can do:

[str(di) if di is None else di for di in d]

Comments

4

Starting Python 3.6 you can do it in shorter form:

d = [f'{e}' for e in d]

hope this helps to someone since, I was having this issue just a while ago.

2 Comments

what does f'{e}' mean here?
It's an "f-string" - Literal string interpolation. You can check more about it in PEP 498. It's worth a while of reading because it's great feature.
3

Using a lengthy and inefficient however beginner friendly for loop it would look like:

d = [1,'q','3', None, 'temp']
e = []

for i in d:
    if i is None: #if i == None is also valid but slower and not recommended by PEP8
        e.append("None")
    else:
        e.append(i)

d = e
print d
#[1, 'q', '3', 'None', 'temp']

Only for beginners, @Martins answer is more suitable in means of power and efficiency

4 Comments

Don't use == None; None is a singleton, using is None is faster and more pythonic and PEP-8 compliant.
Always use is None if that is what you mean. i can be a type that implements comparison to None as True.
@MartijnPieters What is means by singleton ?
An object of which there is only one copy during the lifetime of the program. None, True, False, Ellipsis and NotImplemented are all singletons part of Python itself.
2

List comprehension is the right way to go, but in case, for reasons best known to you, you would rather replace it in-place rather than creating a new list (arguing the fact that python list is mutable), an alternate approach is as follows

d = [1,'q','3', None, 'temp', None]
try:
    while True:
        d[d.index(None)] = 'None'
except ValueError:
    pass

>>> d
[1, 'q', '3', 'None', 'temp', 'None']

Comments

1

I did not notice any answer using lambda..

Someone who wants to use lambda....(Look into comments for explanation.)

#INPUT DATA
d =[1,'q','3', None, 'temp']

#LAMBDA TO BE APPLIED
convertItem = lambda i : i or 'None' 

#APPLY LAMBDA
res = [convertItem(i) for i in d]

#PRINT OUT TO TEST
print(res)

Comments

0

My solution was to match for None and replace it.

def fixlist(l: list):
    for i, v in enumerate(l):
        if v is None:
            l[i] = 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.