0

My requirement: I want to replace nan with ""(empty string)

Example

data = """{"name":"siva","id":"111","grade":"12","job_id":nan,"location":"ananb"}"""

If you see above example, i just want to replace nan(Not a Number) not the string consists of nan(ananb)

Can any one suggest a solution for this?

3 Answers 3

2

A non generic solution for your specific example could be

data.replace(":nan",":")

This wouldn't replace actual values of the dictionary

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

Comments

1

You can use the string.replace method.

data.replace("nan","")

Hope this solves your problem.

4 Comments

it will replace ananb as well, but i just want to replace only nan not other strings conatins nan in it
Think that this will replace any appearance of "nan" in the entire string, and for example will also replace "ananb", can use regex replace and replace every nan sorrounded by \bs
i don't want to replace ananb. i just want to replace nan.
If you know that the nan is always going to be at that specific value in the string, you can use data.replace('nan', '', 1) -> Will only replace the first instance. Otherwise, you have to use regex I'm afraid.
0

Better one would be to replace any match of nan which not sorrounded by other letters using regex ike so:

import re

print(re.sub("\Wnan\W", "", data))

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.